gpt4 book ai didi

c# - 创建一个类并在运行时对其进行装饰

转载 作者:行者123 更新时间:2023-11-30 20:51:12 26 4
gpt4 key购买 nike

我有一个像这样的c#类

public class Info
{
public string PropertyName;
public int PropertyLength;

}

当我读取文件并将数据取回类时,它看起来像

List<Info> information=new List<Info>();

//从文件中读取数据并将其添加回列表的代码

information - is a List collecting multiple entries...

0,1 - elements inside the list..

[0]
PropertyName - FirstName
PropertyLength - 25

[1]
PropertyName - LastName
PropertyLength - 50

我想根据上面的结果在运行时生成一个类

public class GeneratedClass
{

[FieldLength(25)];
public string FirstName;
[FieldLength(50)];
public string LastName;

}

我如何在运行时用例如 FieldLength(这个值来自另一个来源)装饰它以获得如上所述的预期结果?

最佳答案

Reflection.Emit包含许多可帮助您实现此目标的工具:

Reflection emit provides the following capabilities:

...

Define types in modules at run time, create instances of these types, and invoke their methods.

单独(尽管从未使用过),我的理解是 you can also use a TypeDescriptor to achieve this :

TypeDescriptor is an extensible inspection mechanism not just for components but for all Types and for individual instances of any given Type ... TypeDescriptor lets you inspect as well as modify the metadata (add, change and delete) of the target in any conceivable manner. The term target, for the rest of this text will refer to an element of the set of all .NET Framework Types (including Types imported from COM) and all instances of every .NET Framework Type.

关于c# - 创建一个类并在运行时对其进行装饰,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21951396/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com