gpt4 book ai didi

c# - .NET Core 1.1 如何获取当前属性的名称

转载 作者:行者123 更新时间:2023-11-30 19:54:03 24 4
gpt4 key购买 nike

我需要能够访问 .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 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 Framework 中,我们可以像下面这样使用反射。

System.Reflection.MethodBase.GetCurrentMethod().Name;

(我们记得,属性实际上只是幕后的一种方法。)

但是,似乎此功能在 .NET Core 1.1 中不可用——尽管它(可能/将)在 .NET Standard 2.0 中可用。

在这个 GitHub 问题 ( https://github.com/dotnet/corefx/issues/12496 ) 上,有一个关于使用 GetMethodInfoOf 访问属性名称的引用。但是,我无法找到此方法的任何示例,指向可能示例的 GitHub 链接似乎已损坏。

还有什么其他策略或技术可以用来检索当前属性的名称?

非常感谢!

最佳答案

也许我在这里完全误解了您的问题,但是简单地使用 nameof 又如何呢?运营商?

var propName = nameof(MyProperty);

关于c# - .NET Core 1.1 如何获取当前属性的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44163259/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com