C# 如何将Activator.CreateInstance设置为没有构造函数的类型?
例如:C# 如何将Activator.CreateInstance设置为没有构造函数的类型?,c#,C#,例如: class TestType { public int a; public int b; } TestType obj = Activator.CreateInstance(typeof(TestType), 1, 2) as TestType; 然后obj.a==1和obj.b==2?有人知道如何解决我的问题吗?不可能,试试吧 TestType obj = Activator.CreateInstance(typeof(TestType)) as TestType; o
class TestType
{
public int a;
public int b;
}
TestType obj = Activator.CreateInstance(typeof(TestType), 1, 2) as TestType;
然后
obj.a==1
和obj.b==2
?有人知道如何解决我的问题吗?不可能,试试吧
TestType obj = Activator.CreateInstance(typeof(TestType)) as TestType;
obj.a = 1;
obj.b = 2;
这是重载激活器.CreateInstance(类型,参数对象[]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;
}
你把事情弄糊涂了。语法
newtesttype{a=1,b=2}
没有调用构造函数。它是调用隐式或默认构造函数并一次性设置某些属性的快捷方式。但是所有类都有构造函数。至少是含蓄的
我不知道您的最终目标是什么,但是如果您使用Activator
创建实例,那么您可能在编译时没有该类型。因此,您无法通过类型本身访问属性,您需要调用PropertyInfo.SetValue
()
请参见以下示例:
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}");
}
在最后一行代码中,我重新引入了编译时类型,只是为了表明构造的对象按照我们预期的方式设置了成员
一般来说,您最有可能查找扩展某个基本类型或实现某个接口的类型,但很可能是在配置中具有完全限定的类型名的情况,例如。为什么在创建实例后不能分配值。像obj.a=1和obj..b=2一样,您可以添加一个构造函数或方法,或者它是第三方程序集中的一个类吗?1)该类型确实有一个构造函数,除非它是静态类型,否则它至少会有编译器提供的默认构造函数,2)否,框架中没有任何构造函数调用或类似的调用,它们将执行您想要的关于赋值的操作,Antoine下面回答的是您将得到的最接近的构造函数,除非您添加缺少的构造函数。因为TestType类只是一个数据类,没有方法,我有许多数据类。我不想为这些类创建构造函数。我必须通过Reflection创建它们您可以将构造函数语法和对象初始化语法结合起来,所以它是“construct object”和“assign members”的缩写,这意味着您可以这样做:
new TestType(1){b=2}
,前提是该类型有一个接受单个参数的构造函数。@LasseVågsætherKarlsen,但基于这个问题,对OP来说可能太复杂了。。。
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}");
}