以编程方式生成属性 [英] Generate properties programmatically
问题描述
我想加载一个属性文件(这是一个.csv文件,每行都有一个名称和相关的数值),然后按如下方式访问这些属性值: FileLoader.PropertyOne
或FileLoader.PropertyTwo
.问题是我不想为每个值编写一个属性,而是希望它们从文件中生成.所以
I want to load a properties file (it's a .csv file having on each line a name and associated numeric value) and then access those property values like so: FileLoader.PropertyOne
or FileLoader.PropertyTwo
. The problem is I don't want to have to write a property for each value, I want them to be generated from the file. So
public class FileLoader
{
public int Property1 { get; private set; }
}
不是我想要的.这可能吗?我看不到任何方法,因为显然编译器不会知道属性名称.也许类似的东西?
is not what I'm looking for. Is this possible? I can't see any way to do it because obviously the compiler wouldn't know about the property names. Perhaps something similar?
推荐答案
In C# 4.0, you could use the ExpandoObject, link contains good explanation and a couple of use cases, like :
dynamic contact = new ExpandoObject();
contact.Name = "Patrick Hines";
contact.Phone = "206-555-0144";
contact.Address = new ExpandoObject();
contact.Address.Street = "123 Main St";
contact.Address.City = "Mercer Island";
contact.Address.State = "WA";
contact.Address.Postal = "68402";
尽管ExpandoObject的出色之处在于可以动态创建复杂的分层对象,但我想您可以使用它,因为即使是简单的动态定义的对象,它的语法也很闪亮.
Though the awesomeness of the ExpandoObject is to dynamically create complex hierarchical objects, I suppose you could use it in general for it's shiny syntax even for simple dynamically defined objects.
这是关于SO的另一个答案,由写先前链接文章的同一专栏作家添加有关ExpandoObject优点的详细信息
Here is another answer on SO adding details about the benefits of ExpandoObject by the same columnist that wrote the previously linked article
这篇关于以编程方式生成属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!