C# 如何在.NET Core 1.1中获取当前属性的名称
我需要能够访问.NET Core中类的当前属性的名称C# 如何在.NET Core 1.1中获取当前属性的名称,c#,.net,.net-core,system.reflection,C#,.net,.net Core,System.reflection,我需要能够访问.NET Core中类的当前属性的名称 public class MyClass { private string _myProperty; public string MyProperty { get => _myProperty; set { // GOAL: Check my property name and then do something with that inf
public class MyClass
{
private string _myProperty;
public string MyProperty
{
get => _myProperty;
set
{
// GOAL: Check my property name and then do something with that information.
// The following used to works in the full .NET Framework but not .NET Core.
// var propName = System.Reflection.MethodBase.GetCurrentMethod().Name;
_myProperty = value;
}
}
}
在完整的.NET框架中,我们可以使用反射,如下所示
System.Reflection.MethodBase.GetCurrentMethod().Name;
(我们记得,属性实际上只是一种隐藏的方法。)
但是,该功能在.NET Core 1.1中似乎不可用,尽管它(可能/将)在.NET Standard 2.0中可用
在这个GitHub问题()中,有一个引用使用GetMethodInfoOf
访问属性名。但是,我一直无法找到此方法的任何示例,指向可能示例的GitHub链接似乎已断开
可以使用什么其他策略或技术来检索当前属性的名称
非常感谢 也许我完全误解了您的问题,但是简单地使用操作符怎么样
var propName = nameof(MyProperty);
那么nameof(MyProperty)呢?我相信这种方法的挑战是,我必须在nameof函数中包含属性。我不知道如何从属性本身中获取当前属性的句柄。正是@mm8所说的:
nameof(MyProperty)
。您不需要获取属性的句柄,这是一个编译时、语言级别的东西。