r.z*_*rei 3 c# reflection indexer properties propertybag
访问像javascript语言这样的c#类属性会让生活变得更轻松.
我们如何在C#中做到这一点?
例如:
someObject["Property"]="simple string";
Console.WriteLine(someObject["FirstName"]);
Run Code Online (Sandbox Code Playgroud)
以下是通过添加几行代码在类中启用类似属性包的功能的方法:
partial class SomeClass
{
private static readonly PropertyDescriptorCollection LogProps = TypeDescriptor.GetProperties(typeof(SomeClass));
public object this[string propertyName]
{
get { return LogProps[propertyName].GetValue(this); }
set { LogProps[propertyName].SetValue(this, value); }
}
}
Run Code Online (Sandbox Code Playgroud)