使用system.reflection列出一个类文件 [英] using system.reflection to list a class fileds
问题描述
我需要获取一个列表来存储所有字段-类中的值
i need to get a list to store all fields - values in a class
该类只是我下面粘贴的一些公共 const字符串
变量.
the class is just a few of public const string
variables as i pasted below.
public class HTDB_Cols
{
public class TblCustomers
{
public const string CustID = "custID",
Name = "name",
CustType = "custType",
AddDate = "addDate",
Address = "address",
City = "city",
Phone = "phone",
Cell = "cell";
}
}
这是一种返回字符串列表的方法,该方法使我能够使用代表我所有表列名称的字符串列表,尽管由于出现错误,某些东西无法使用此代码
this is a method that returns a list of strings that enables me to have a list of strings representing all my tables columns names , though somthing is not working with this code as i get an error
"非静态字段需要目标".
public class GetClassFields
{
public static List<string> AsList(string TableName)
{
return typeof(HTDB_Cols).GetNestedTypes()
.First(t => String.Compare(t.Name, TableName, true) == 0)
.GetFields()
.Select(f => f.GetValue(null) as string)
.ToList();
}
}
尝试如下使用它:
foreach (string tblCol in RobCS_212a.Utils.Reflct.GetClassFields.AsList (DBSchema.HTDB_Tables.TblCustomers))
{
Response.Write(string.Concat(tblCol, "<br />"));
}
在类型'DBSchema.HTDB_Cols + TblTimeCPAReport'上定义的字段'tbName'不是目标对象上在'DBSchema.HTDB_Cols'类型的字段.
Field 'tbName' defined on type 'DBSchema.HTDB_Cols+TblTimeCPAReport' is not a field on the target object which is of type 'DBSchema.HTDB_Cols'.
推荐答案
您的代码已关闭.有两个问题,都位于linq select方法调用的参数中:
Your code was close. There were two issues, both located in the arguments to your linq select method call:
-
您的类HTDB_Cols是一个非静态类,您尝试检索的字符串值是实例成员.因此,当您尝试从类中拉出实例成员时,必须将类的实例传递给FieldInof.GetValue方法.在下面的代码中,我在变量"instanceOfClass"中创建您的类的实例.您可以在 FieldInfo类
从FieldInfo.GetValue返回的值是一个对象.您必须使用ToString方法或(string)类型转换将其显式转换为字符串.
The value returned from FieldInfo.GetValue is an object. You have to explicitly cast it to a string using the ToString method or the (string) cast.
通过这两个更改,您的方法可以工作.清单如下:
With these two changes your method works. A listing is as follows:
public class GetClassFields
{
public static List<string> AsList(string tbl)
{
var instanceOfClass = new HTDB_Cols();
return typeof(HTDB_Cols).GetNestedTypes()
.First(t => String.Compare(t.Name, tbl, true) == 0)
.GetFields()
.Select(f => f.GetValue(instanceOfClass).ToString())
.ToList<String>();
}
}
您可以按以下方式调用此函数:
You can call this function as follows:
var fields = GetClassFields.AsList("TblCustomers");
返回所需信息:
这篇关于使用system.reflection列出一个类文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!