1

我需要实现一个方法,该方法返回一个基于类型的对象。

 public interface IBase
{ 
}
public class Base1 : IBase { }
public class Base2 : IBase { }
public class Base3 : IBase { }
public class MyClass
{
    public IBase GetObject<T>() where T:IBase
    {
        // should return the object based on type.
        return null;
    }

}

我需要像在 GetObject 方法中那样维护字典吗?

            Dictionary<Type, IBase> test = new Dictionary<Type, IBase>();

有没有更好的方法?

[编辑]: - 我不想每次都创建对象。我需要将它保存在内存中以及有电话时。我想从那里返回对象。除了字典还有其他方法吗?

4

3 回答 3

3
public class MyClass {
    public IBase GetObject<T>() where T:IBase, new() // EDIT: Added new constraint 
    {
        // should return the object based on type.
        return new T();
    }

}
于 2012-11-20T03:52:19.960 回答
3

在您的情况下,您有两种方法:

1)创建自己的收藏并自己维护(类似这样)

public interface IBase {}
public class Base1 : IBase { public int x; }
public class Base2 : IBase { public int y; }
public class Base3 : IBase { public int z; }

public class MyClass
{
    Dictionary<Type, IBase> m_typesCollection;

    public MyClass()
    {
        // for example
        m_typesCollection = new Dictionary<Type, IBase>();
        m_typesCollection.Add(typeof(Base1), new Base1());
        m_typesCollection.Add(typeof(Base2), new Base2());
    }

    public IBase GetObject<T>()
        where T : IBase, new()
    {
        if (m_typesCollection.ContainsKey(typeof(T)))
            return m_typesCollection[typeof(T)];
        m_typesCollection.Add(typeof(T), new T());
        return m_typesCollection[typeof(T)];
    }
}

2) - 使用依赖注入容器作为你的类型的集合

于 2012-11-21T06:18:19.713 回答
2

您可以将new()约束添加到泛型类型参数。请阅读类型参数的约束(C# 编程指南)。然后它看起来有点像这样:

public T GetObject<T>() where T : IBase, new()
{
    return new T();
}

并使用它

IBase b = GetObject<Base1>();

实际上,有一个基于类型创建对象的内置方法,即Activator.CreateInstance 方法

IBase b = Activator.CreateInstance<Base1>();
于 2012-11-20T03:56:01.980 回答