从泛型类创建实例?

时间:2013-11-29 21:22:35

标签: c# reflection

我有以下课程:

public abstract class Repository<TEntity, TIdentifier> : IRepository<TEntity, TIdentifier> where TEntity : class
{ --- }

public abstract class BaseBusinessObject<TEntity, TIdentifier> : Repository<TEntity, TIdentifier> where TEntity : class
    { --- }

public class AttachmentBusinessObject : BaseBusinessObject<Attachment, long>
    { --- }

某处,我所拥有的唯一内容是字符串中的“AttachmentBusinessObject”,字符串中的“附件”TEntity

如何创建BaseBusinessObjectAttachmentBusinessObject

的实例

2 个答案:

答案 0 :(得分:2)

您可以使用Activator.CreateInstance执行此操作:

public class Base
{ }

public class Derived : Base
{ }

[TestMethod]
public void BaseDerivedTest()
{
    string type = "Derived"; // type is found somewhere upstream
    if (type == "Derived")
    {
        var b = Activator.CreateInstance(typeof(Derived).BaseType);
        Assert.IsInstanceOfType(b, typeof(Base));
    }
}

答案 1 :(得分:1)

我不确定我是否正确理解你,但你可能想看看Activator.CreateInstance

这样的事情:

var yourObject
    = Activator.CreateInstance(null, "AttachmentBusinessObject").Unwrap();

这不是很有用,但如果你想传递对象,因为CreateInstance不知道类型是什么,所以它只返回object

绕过它的一种方法 - 你将要创建实例的任何类都可以实现一个通用接口。所以你最终会得到类似的东西:

IBusinessObject yourObject
    = (IBusinessObject)Activator.CreateInstance(null, "AttachmentBusinessObject").Unwrap();

另一种选择是使用上面的第一行代码,然后在if / else语句中测试正确的类类型:

Type objType = yourObject.GetType();

if (objType == typeof(AttachmentBusinessObject))
{
    var myAttachBusObject = (AttachmentBusinessObject)yourObject;
    ...
}
else
    ...