Pat*_*cus 69 c# reflection properties
我要做的是使用字符串在类中设置属性的值.例如,我的类具有以下属性:
myClass.Name
myClass.Address
myClass.PhoneNumber
myClass.FaxNumber
Run Code Online (Sandbox Code Playgroud)
所有字段都是字符串类型,所以我提前知道它总是一个字符串.现在我希望能够使用字符串设置属性,就像使用DataSet对象一样.像这样的东西:
myClass["Name"] = "John"
myClass["Address"] = "1112 River St., Boulder, CO"
Run Code Online (Sandbox Code Playgroud)
理想情况下,我只想分配一个变量,然后使用变量中的字符串名称设置属性
string propName = "Name"
myClass[propName] = "John"
Run Code Online (Sandbox Code Playgroud)
我正在阅读关于反思的内容,也许是这样做的方法,但我不确定如何设置它,同时在课堂上保持属性访问不变.我想仍然可以使用
myClass.Name = "John"
Run Code Online (Sandbox Code Playgroud)
任何代码示例都非常棒.
Tig*_*ran 92
您可以添加索引器属性,伪代码:
public class MyClass
{
public object this[string propertyName]
{
get{
// probably faster without reflection:
// like: return Properties.Settings.Default.PropertyValues[propertyName]
// instead of the following
Type myType = typeof(MyClass);
PropertyInfo myPropInfo = myType.GetProperty(propertyName);
return myPropInfo.GetValue(this, null);
}
set{
Type myType = typeof(MyClass);
PropertyInfo myPropInfo = myType.GetProperty(propertyName);
myPropInfo.SetValue(this, value, null);
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以向类中添加索引器并使用反射来获取属性:
using System.Reflection;
public class MyClass {
public object this[string name]
{
get
{
var properties = typeof(MyClass)
.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var property in properties)
{
if (property.Name == name && property.CanRead)
return property.GetValue(this, null);
}
throw new ArgumentException("Can't find property");
}
set {
return;
}
}
}
Run Code Online (Sandbox Code Playgroud)