如何将此方法作为扩展方法添加到我的类的属性中?
我有一个方法,我想将此方法作为扩展方法添加到我的类的属性中。 该方法给出一个表达式作为输入参数。该方法如下:
public static string GetPropertyName<T>(Expression<Func<T>> propertyExpression)
{
return (propertyExpression.Body as MemberExpression).Member.Name;
}
我想使用此方法,如下例:
string propertyName = MyClass.Property1.GetPropertyName();
可以吗?如果是,解决办法是什么?
I have a method and I want to add this method as an extension method to properties of my class.
This method give an expression as input parameter. The method is like below :
public static string GetPropertyName<T>(Expression<Func<T>> propertyExpression)
{
return (propertyExpression.Body as MemberExpression).Member.Name;
}
I want to use this method like below example :
string propertyName = MyClass.Property1.GetPropertyName();
Is it possible? if yes, what is the solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,这是不可能的。尚不清楚
MyClass
是否是类的名称(并且Property1
是静态属性),或者它是否是实例属性并且MyClass.Property1
根本就不是有效的会员访问权限。如果是后者,您可能希望将您的方法更改为类似:并将其调用为:
或者您可以使用带有泛型方法的泛型类,以便
string
可以推断:那就是这样的:
No, it's not possible to do that. It's not clear whether
MyClass
is the name of a class (andProperty1
is a static property) or whether it's an instance property andMyClass.Property1
simply isn't a valid member access. If it's the latter, you probably want to change your method to something like:and call it as:
Or you could use a generic class with a generic method, so that
string
can be inferred:That would be something like:
扩展方法是特定于类型的(即使它们是通用的),如果没有可用于该类型的所有项目的相同扩展方法,则无法为属性提供扩展方法。
如果您有特定类型的扩展方法,无论它是属性、局部变量还是类成员,扩展方法仍然可用。
Extension methods are type-specific (even when they are generic), you can't have an extension method for a property without having the same extension method available to all items that are of that type.
If you have an extension method for a specific type, it won't matter if it's a Property or a local variable or a class member, the extension method will still be availabe.
您无法创建“静态”扩展方法。
扩展方法是“实例”方法。
您可以只提供一个辅助类:-
You can't create "static" extension methods.
Extension methods are "instance" methods.
You could just provide a helper class:-
我显然不是像乔恩这样的专家,但在我看来,你想要的东西相当简单(这就是我怀疑的原因,因为乔恩显然是一个参考人!;-)):
它编译并满足要求,从什么我可以看到。您可能应该自己找到它,因为您从一开始就谈到了扩展方法......
I'm clearly not an expert like Jon but this seems to me that what you want and is fairly simple (that's why I doubt, since Jon is clearly a reference person ! ;-)) :
It compiles and meet the requirements, from what I can see. You probably should have found it yourself, since you spoke about an extension method from start...