c# - 我如何动态创建类的对象?

标签 c# .net

我有一个类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/

相关文章:

c# - 同步实现异步接口(interface)?

c# - if 语句在一行上,其中包含 html

c# - .NET序列化: Best practice to map classes to elements and properties to attributes?

c# - 使用 C# 检查进程是否正在远程系统上运行

c# - 正则表达式中的可选组返回太多匹配项

c# - 对于以 0x85 字符结尾的文件路径(Windows 8),.Net 4.6.1 和 4.6.2 之间的奇怪 Path.GetFullPath 行为不同

c# - 方法的执行时间在增加,为什么会这样?

c# - 使用 async-await 进行数据库查询——这如何节省线程?

c# - 在缓存中找不到元素 - 也许页面在查找后已更改 c#

c# - 如何从Xpath中的父节点获取所选节点的位置