访问 C# 类属性(如 JavaScript 语言)将使生活变得更加轻松。
我们如何在 C# 中做到这一点?
例如:
someObject["Property"]="simple string";
Console.WriteLine(someObject["FirstName"]);
以下是如何通过添加几行代码在类中启用类似属性包的功能:
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); }
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)