Dav*_*vid 3 c# properties instance
我有一个与另一个问题非常相似的问题:将属性名称作为字符串.
他的解决方案结束了
// Static Property
string name = GetPropertyName(() => SomeClass.SomeProperty);
// Instance Property
string name = GetPropertyName(() => someObject.SomeProperty);
Run Code Online (Sandbox Code Playgroud)
我想要的是具有类似于静态属性的语法,但是对于实例属性.
原因是我现在有代码使用反射来获取集合中所有对象的属性值,但我必须将其作为硬编码字符串传递.
示例代码:
double Sum = AmountCollection.Sum("thatfield");
Run Code Online (Sandbox Code Playgroud)
嗯,这很好用,但如果"thatfield"被重命名,代码将不再有效.编译器无法检查它,因为它只是一个字符串.此外,Get References也不会出于同样的原因.
那么,有没有办法实现从实例属性轻松获取属性名称的目标(即;只是一个函数调用)?
谢谢.
试试这个:
string name = GetPropertyName(() => default(SomeClass).SomeInstanceProperty);
Run Code Online (Sandbox Code Playgroud)
您可能会收到有关"始终导致System.NullReferenceException"的编译器警告,但实际上并未发生这种情况,因为您没有执行该表达式,这意味着您可以安全地丢弃此警告.如果你想摆脱它,要么通过pragma禁用它,要么只是将default()调用移动到这样的函数:
public static T Dummy<T>() {
return default(T);
}
string name = GetPropertyName(() => Dummy<SomeClass>().SomeInstanceProperty);
Run Code Online (Sandbox Code Playgroud)