繁体   English   中英

如何Activator.CreateInstance一个没有构造函数的类型?

[英]How to Activator.CreateInstance a type which have not constructors?

例如:

class TestType
{
   public int a;
   public int b;
}

TestType obj = Activator.CreateInstance(typeof(TestType), 1, 2) as TestType;

那么obj.a==1obj.b==2 有人知道如何解决我的问题吗?

不可能,试试吧

TestType obj = Activator.CreateInstance(typeof(TestType)) as TestType;
obj.a = 1;
obj.b = 2;
TestType obj = Activator.CreateInstance(typeof(TestType), 1, 2) as TestType;

这是重载Activator.CreateInstance(type,params object [] args); 其中args是构造函数的输入。 因此,您可以使用Antoines解决方案或将测试类型类更改为:

TestType obj = Activator.CreateInstance(typeof(TestType), 1, 2) as TestType;

class TestType
{
    public TestType(int a, int b)
    {
        this.a = a;
        this.b = b;
    }

    public int a;
    public int b;
}

你是混乱的事情。 语法new TestType { a=1, b=2 } 调用构造函数。 它是调用隐式或默认构造函数并一次性设置某些属性的快捷方式。 但是所有类都有构造函数。 至少是隐含的。

我不知道你的最终目标是什么,但如果你使用Activator来创建一个实例,那么你可能在编译时没有这个类型。 因此,您无法通过类型本身访问属性,您需要调用PropertyInfo.SetValuehttps://docs.microsoft.com/en-us/dotnet/api/system.reflection.propertyinfo.setvalue?view= netframework-4.7.2

请参阅以下示例:

class TestType
{
    public int a;
    public int b;
}

void Main()
{
    var typeName = typeof(TestType).FullName; // we have a string from here on

    var type = Assembly.GetExecutingAssembly().GetTypes().FirstOrDefault(x => x.FullName == typeName); // get the type based on the name

    var obj = Activator.CreateInstance(type); // object of this type, but without compile time type info

    var member = type.GetField("a"); // we know, that this is a field, not a property   
    member.SetValue(obj, 1); // we set value to 1
    member = type.GetField("b");
    member.SetValue(obj, 2); // we set value to 2

    Console.Write($"See values: a={((TestType)obj).a}, b={((TestType)obj).b}");
}

在最后一个代码行中,我重新引入了编译时类型,只是为了表明构造的对象具有我们期望它们设置的成员集。

通常,您很可能会查找扩展某些基类型或实现接口的类型,但例如,当您从配置中获得完全限定的类型名称时,可能就是这种情况。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM