如何在常量c#中使用getproperty

S D*_*mar 1 .net c# visual-studio

我正在尝试使用选址值获取恒定值,但我无法实现这一点,你可以帮助我这样做吗

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

提前致谢

Dav*_*idG 5

首先,您需要使用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
Run Code Online (Sandbox Code Playgroud)