using system.reflection to list a class fileds

2020-05-03 10:59发布

问题:

i need to get a list to store all fields - values in a class

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

" Non-static field requires a target".

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();

        }
}

trying to use it as follows :

foreach (string tblCol in RobCS_212a.Utils.Reflct.GetClassFields.AsList      (DBSchema.HTDB_Tables.TblCustomers))
{
    Response.Write(string.Concat(tblCol, "<br />"));
}

Field 'tbName' defined on type 'DBSchema.HTDB_Cols+TblTimeCPAReport' is not a field on the target object which is of type 'DBSchema.HTDB_Cols'.

回答1:

Your code was close. There were two issues, both located in the arguments to your linq select method call:

  • Your class HTDB_Cols is a non-static class and the string values you are trying to retrieve are instance members. Thus when you are trying to pull instance members out of a class, you have to pass an instance of the class to the FieldInof.GetValue method. In my code below I create an instance of your class in the variable "instanceOfClass". You can see this in the documentation for the FieldInfo class

  • 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");

which returns the desired information: