【问题标题】:how to use getproperty in constant c#如何在常量c#中使用getproperty
【发布时间】:2021-09-29 17:47:50
【问题描述】:

我正在尝试使用选址值获取常量值,但我无法实现,您能帮我这样做吗

using System;
public static class Constants
{
    public static class HostServer
    {
        public static string ABC = "abc.com";
    }
    public static class WMS
    {
        public const string URL = "/create/user";
    }
}
public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");
        var x = Constants.GetType().GetProperty("ABC").GetValue(Constants, null).ToString();
        Console.WriteLine(x);
    }
}

提前致谢

【问题讨论】:

  • 试试var x = typeof(Constants).GetProperty("...
  • 问题是,为什么要使用反射?
  • var x = typeof(Constants).GetProperty("ABC").GetValue(Constants,null).ToString(); 我得到了以下错误'Constants' is a 'type' but is used like a 'variable'
  • @DavidG 你能推荐一个上面的例子吗
  • 我的意思是,你为什么不能直接使用var x = Constants.HostServer.ABC;

标签: c# .net visual-studio


【解决方案1】:

首先,你需要使用GetField,而不是GetProperty。其次,您应该指定绑定标志,因为常量本质上是静态的。最后,您需要使用类的完整类型名称,因为您有嵌套类。有了所有这些,这将为您提供常量值:

var x = typeof(Constants.HostServer) // <-- Use full class name here
   .GetField("ABC", BindingFlags.Public | BindingFlags.Static) // <-- binding flags
   .GetValue(null); // <-- static fields don't need an instance object

【讨论】:

  • 工作很好,谢谢
  • @SDeepakkumar 我会鼓励你做一些空检查,GetField 可以返回 null... 类似:var x = typeof(Constants.HostServer) // &lt;-- Use full class name here .GetField("ABC", BindingFlags.Public | BindingFlags.Static) // &lt;-- binding flags ?.GetValue(null);
猜你喜欢
  • 1970-01-01
  • 2010-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多