我有一个类,我从另一个类定义一个常量将读取这些常量或类的属性和属性的内容。像读取类的元数据之类的东西。 像这样的东西:
namespace Ventanas._01Generales
{
class Gral_Constantes
{
public class Cat_Productos
{
public const String Tabla_Productos = "Cat_Productos";
public const String Campo_Producto_ID = "Producto_ID";
}
public class Cat_Grupos_Productos
{
public const String Tabla_Grupos_Productos = "Cat_Grupos_Productos";
public const String Campo_Grupo_Producto_ID = "Grupo_Producto_ID";
}
}
}
在其他课程中,例如像这样的
namespace Ventanas._01Generales
{
class Pinta_Ventana
{
public void Crea_Insert()
{
foreach(Properties p in Cat_Producto.Properties)
{
miControl.Text = p.value; //show "Cat_Grupos_Productos"
miControl.Name = p.value; //show Tabla_Grupos_Productos
}
}
}
}
答案 0 :(得分:1)
您需要Type.GetProperties
(MSDN)此代码可以使用:
foreach (PropertyInfo p in typeof(Cat_Producto).GetProperties())
{
...
}
现在有几点需要注意:
您正在使用反射这实在很慢,而且您使用它的事实表明您可能会做一些非常错误的事情。
如果您输出示例代码的方式,则只显示最后一个属性的信息,因为您永远不会让UI更新。
您的代码实际上没有属性,它们有const字段,因此此代码不会返回任何属性。使它们的属性可以使用此方法。如果您想要字段版本,可以使用Type.GetFields
。
答案 1 :(得分:1)
看起来您想要使用System.Reflection命名空间。如果您想获取公共const字符串的名称,则需要使用MemberInfo。这应该让你开始:
MemberInfo[] members = typeof(MyClass).GetMembers();
foreach(MemberInfo m in members)
{
//do something with m.Name
Console.WriteLine(m.Name);
}