C# 字符串到变量名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1293549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
string to variable name
提问by Mohanavel
I have class(Customer) which holds more than 200 string variables as property. I'm using method with parameter of key and value. I trying to supply key and value from xml file. For this, value has to be substituted by Customer class's property(string variables).
我有 class(Customer) ,它包含 200 多个字符串变量作为属性。我正在使用带有键和值参数的方法。我试图从 xml 文件中提供键和值。为此,值必须由 Customer 类的属性(字符串变量)替换。
ie
IE
Customer
{
public string Name{return _name};
public string Address{return _address};
}
CallInput
{
StringTempelate tempelate = new StringTempelate();
foreach(item in items)
tempelate .SetAttribure(item.key, item.Value --> //Say this value is Name, so it has to substitute Customer.Name
}
is it possible?
是否可以?
采纳答案by David
You can use reflection to set the properties 'by name'.
您可以使用反射来“按名称”设置属性。
using System.Reflection;
...
myCustomer.GetType().GetProperty(item.Key).SetValue(myCustomer, item.Value, null);
You can also read the properties with GetValue, or get a list of all property names using GetType().GetProperties(), which returns an array of PropertyInfo (the Name property contains the properties name)
您还可以使用 GetValue 读取属性,或使用 GetType().GetProperties() 获取所有属性名称的列表,它返回一个 PropertyInfo 数组(Name 属性包含属性名称)
回答by Jon Skeet
Well, you can use Type.GetProperty(name)
to get a PropertyInfo
, then call GetValue
.
好吧,您可以使用Type.GetProperty(name)
来获取PropertyInfo
,然后调用GetValue
。
For example:
例如:
// There may already be a field for this somewhere in the framework...
private static readonly object[] EmptyArray = new object[0];
...
PropertyInfo prop = typeof(Customer).GetProperty(item.key);
if (prop == null)
{
// Eek! Throw an exception or whatever...
// You might also want to check the property type
// and that it's readable
}
string value = (string) prop.GetValue(customer, EmptyArray);
template.SetTemplateAttribute(item.key, value);
Note that if you do this a lot you may want to convert the properties into Func<Customer, string>
delegate instances - that will be muchfaster, but more complicated. See my blog post about creating delegates via reflectionfor more information.
需要注意的是,如果你这样做了很多,你可能想要的属性转换成Func<Customer, string>
委托实例-这将是多快,而是变得更复杂。有关更多信息,请参阅我关于通过反射创建委托的博客文章。
回答by MattH
Use reflection and a dictionary object as your items collection.
使用反射和字典对象作为您的项目集合。
Dictionary<string,string> customerProps = new Dictionary<string,string>();
Customer myCustomer = new Customer(); //Or however you're getting a customer object
foreach (PropertyInfo p in typeof(Customer).GetProperties())
{
customerProps.Add(p.Name, p.GetValue(customer, null));
}
回答by Marc Gravell
Reflection is an option, but 200 properties is... a lot. As it happens, I'm working on something like this at the moment, but the classes are created by code-gen. To fit "by name" usage, I've added an indexer (during the code generation phase):
反射是一种选择,但 200 个属性是……很多。碰巧的是,我目前正在做这样的事情,但这些类是由代码生成创建的。为了适应“按名称”的用法,我添加了一个索引器(在代码生成阶段):
public object this[string propertyName] {
get {
switch(propertyName) {
/* these are dynamic based on the the feed */
case "Name": return Name;
case "DateOfBirth": return DateOfBirth;
... etc ...
/* fixed default */
default: throw new ArgumentException("propertyName");
}
}
}
This gives the convenience of "by name", but good performance.
这提供了“按名称”的方便,但性能良好。