所以这看起来非常基本,但我无法让它发挥作用.我有一个Object,我使用反射来获取它的公共属性.其中一个属性是静态的,我没有运气.
Public Function GetProp(ByRef obj As Object, ByVal propName as String) as PropertyInfo
Return obj.GetType.GetProperty(propName)
End Function
Run Code Online (Sandbox Code Playgroud)
上面的代码适用于Public Instance属性,到目前为止我只需要它.据说我可以使用BindingFlags来请求其他类型的属性(私有,静态),但我似乎找不到合适的组合.
Public Function GetProp(ByRef obj As Object, ByVal propName as String) as PropertyInfo
Return obj.GetType.GetProperty(propName, Reflection.BindingFlags.Static Or Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Public)
End Function
Run Code Online (Sandbox Code Playgroud)
但是,请求任何静态成员返回任何内容..NET反射器可以很好地看到静态属性,所以很明显我在这里遗漏了一些东西.
我试图在一个简单的静态类中循环一些静态属性,以便用它们的值填充组合框,但是遇到了困难.
这是简单的类:
public static MyStaticClass()
{
public static string property1 = "NumberOne";
public static string property2 = "NumberTwo";
public static string property3 = "NumberThree";
}
Run Code Online (Sandbox Code Playgroud)
...以及试图检索值的代码:
Type myType = typeof(MyStaticClass);
PropertyInfo[] properties = myType.GetProperties(
BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
foreach (PropertyInfo property in properties)
{
MyComboBox.Items.Add(property.GetValue(myType, null).ToString());
}
Run Code Online (Sandbox Code Playgroud)
如果我不提供任何绑定标志,那么我得到大约57个属性,包括System.Reflection.Module模块和我不关心的各种其他继承的东西.我的3个声明的属性不存在.
如果我提供其他标志的各种组合,那么它总是返回0属性.大.
我的静态类是否真的在另一个非静态类中声明是否重要?
我究竟做错了什么?
我正在尝试使用选址值获取恒定值,但我无法实现这一点,你可以帮助我这样做吗
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)
提前致谢