如何实现基于传递的类型返回对象的方法

时间:2012-11-20 03:49:50

标签: c# generics

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

 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>();

还有更好的方法吗?

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

3 个答案:

答案 0 :(得分: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();
    }

}

答案 1 :(得分: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) - 使用依赖注入容器作为类型的集合

答案 2 :(得分:2)

您可以将new()约束添加到泛型类型参数中。请阅读Constraints on Type Parameters (C# Programming Guide)。然后看起来会像这样:

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

并使用它

IBase b = GetObject<Base1>();

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

IBase b = Activator.CreateInstance<Base1>();