我有一个类MyClass
:
public class OPCTag
{
public string tagName;
public string tagOvationMatch;
public string tagValue;
}
我知道如何手动创建类的对象,但如何动态创建此类的对象?例如,要在 for
循环中创建它:
for (int i=0; i< 10; i++)
{
//CREATE OBJECT DYNAMICALLY
}
在它之后获取 MyClass 的 10 个对象。
最佳答案
如果您的意思是简单地创建一个始终具有相同类型的类的实例,那么这对您来说就足够了:
List<OPCTag> list = new List<OPCTag>();
for (int i = 0; i < 10; i++)
{
// Create object of OPCTag
var obj = new OPCTag();
// Set value for 'tagName' property
obj.tagName = "New value of 'tagName'";
// Get value of 'tagName' property
var tagNameValue = obj.tagName;
list.Add(obj);
}
// Set value of 4th element 'tagName' property
list[4].tagName = "This is 4th element";
// Get value of 4th element 'tagName' property
var valueOf4thTag = list[4].tagName;
但是如果你想动态创建未知类型的类,你应该使用反射:
// Type namespace and name
string typeName = typeof(OPCTag).FullName; // MyNamespace.OPCTag
List<Object> list = new List<Object>();
for (int i = 0; i < 10; i++)
{
// Create object dynamically from string type
var obj = Type.GetType(typeName).GetConstructor(new Type[0]).Invoke(new object[0]);
// Set value for 'tagName' property
obj.GetType().GetProperty("tagName").SetValue(obj, "New value for 'tagName'");
// Get value from 'tagName' property
string tagNameValue = (string)obj.GetType().GetProperty("tagName").GetValue(obj);
list.Add(obj);
}
关于c# - 我如何动态创建类的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42921630/