简体   繁体   English

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

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

For example: 例如:

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

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

Then obj.a==1 and obj.b==2 ? 那么obj.a==1obj.b==2 Does someone knows how to solve my problem? 有人知道如何解决我的问题吗?

Impossible, try instead 不可能,试试吧

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

This is the overload Activator.CreateInstance(type, params object[] args); 这是重载Activator.CreateInstance(type,params object [] args); where args are the input for the constructor. 其中args是构造函数的输入。 So you can use either Antoines solution or change the test type class to: 因此,您可以使用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;
}

You are confusing things. 你是混乱的事情。 The syntax new TestType { a=1, b=2 } is not calling the constructor. 语法new TestType { a=1, b=2 } 调用构造函数。 It is a shortcut for calling the implicit or default constructor and setting some properties in one shot. 它是调用隐式或默认构造函数并一次性设置某些属性的快捷方式。 But all classes have constructors. 但是所有类都有构造函数。 At least the implicit one. 至少是隐含的。

I don't know what is your final goal, but if you are using Activator to create an instance, then you probably don't have the type at compile time. 我不知道你的最终目标是什么,但如果你使用Activator来创建一个实例,那么你可能在编译时没有这个类型。 Thus you can't access the properties via the type itself, you will need to call PropertyInfo.SetValue ( https://docs.microsoft.com/en-us/dotnet/api/system.reflection.propertyinfo.setvalue?view=netframework-4.7.2 ) 因此,您无法通过类型本身访问属性,您需要调用PropertyInfo.SetValuehttps://docs.microsoft.com/en-us/dotnet/api/system.reflection.propertyinfo.setvalue?view= netframework-4.7.2

See following example: 请参阅以下示例:

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}");
}

In this last code row I have reintroduced the compile-time type, just to show that the constructed object has the members set as we expect them to be set. 在最后一个代码行中,我重新引入了编译时类型,只是为了表明构造的对象具有我们期望它们设置的成员集。

In general you will most likely look for types that extend some base type or implement an interface, but it might well be cases when you have the fully qualified type name from the configuration for example. 通常,您很可能会查找扩展某些基类型或实现接口的类型,但例如,当您从配置中获得完全限定的类型名称时,可能就是这种情况。

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

相关问题 Activator.CreateInstance - 如何创建具有参数化构造函数的类的实例 - Activator.CreateInstance - How to create instances of classes that have parameterized constructors 如何为各种构造函数做Activator.CreateInstance? - How to do Activator.CreateInstance for various constructors? 具有动态类型的Activator.CreateInstance - Activator.CreateInstance with dynamic Type Activator.CreateInstance和Activator.CreateInstance之间的区别<Type> - difference between Activator.CreateInstance and Activator.CreateInstance<Type> 如何修复Activator.CreateInstance失败与MissingMethodException“未找到类型的构造函数”? - How to fix Activator.CreateInstance failing with MissingMethodException “Constructor on type not found”? 如何使用Activator.CreateInstance从系统dll中加载类型? - How to load type from system dll using Activator.CreateInstance? 如何将object []传递给Activator.CreateInstance(type,params object []) - How to pass object[] to Activator.CreateInstance(type, params object[]) 如何动态地将类型传递给Activator.CreateInstance(object)? - How to pass type dynamically to Activator.CreateInstance(object)? Activator.CreateInstance(Type T)返回null - Activator.CreateInstance(Type T) returns null Activator.CreateInstance-无法使用返回类型 - Activator.CreateInstance - Not able to use the return type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM