开发者

c# reflecting on properties or other member types

开发者 https://www.devze.com 2023-03-11 21:49 出处:网络
I\'m using a tool called filehelpers, which defines a class on the fly for purposes of file import.The class file might look like:

I'm using a tool called filehelpers, which defines a class on the fly for purposes of file import. The class file might look like:

[DelimitedRecord(",")]
[IgnoreFirst(1)]
public class TestNoPrimaryKey
{

[FieldConverter(ConverterKind.Decimal, ".")]
[FieldQuoted()开发者_C百科]
public decimal Value;

[FieldQuoted('"', QuoteMode.OptionalForRead, MultilineMode.AllowForRead)]
public String aString;

}

This is correctly created in code from what I can see. Next I need to create a datatable in a comparable format, so I can do a SQL insert. Through kind help on SO I have this code which accepts the type (defined above) and purports to generate the typed datatable columns for me:

public static DataTable TypeToEmptyDataTable(Type myType)
{
    DataTable dt = new DataTable();

    foreach (PropertyInfo info in myType.GetProperties())
    {
        dt.Columns.Add(new DataColumn(info.Name, info.PropertyType));
    }

    return dt;
}

Unfortunately, it does not find any properties and returns a datatable with no columns. Now I'm thinking - if the get; set; etc isn't specified in the class maybe they aren't 'properties' per se. Maybe getMembers is what I need? I tried that but returning info.MemberType did not work.

Any thoughts on how to get the names/types out of my class? I don't believe I can add the get/set because that class layout is required by the filehelpers tool I'm using.

Thanks!


You haven't written any properties in the code above - you've declared fields. The get and set does indeed make a very significant difference :)

If you want to get fields, just use GetFields - but I'd recommend that you make them properties instead. Properties work better in terms of binding etc, as well as generally being a better start towards encapsulation.


This addition to @Jon Skeet answer ...........

Read value of your fields like this :

Right now you are reading properties not fileds of the classes

Type type = typeof(ReflectionTest); // Get type pointer
FieldInfo[] fields = type.GetFields(); // Obtain all fields
foreach (var field in fields) // Loop through fields
{
      ///you code 
}


Use get field with binding flags

myType.GetFields(System.Reflection.BindingFlags.Public |
             System.Reflection.BindingFlags.Static |
             System.Reflection.BindingFlags.Instance |
             System.Reflection.BindingFlags.FlattenHierarchy |
             System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.GetProperty);
0

精彩评论

暂无评论...
验证码 换一张
取 消