与基类和子类的反射

时间:2013-09-24 11:59:12

标签: c# class reflection

我有一个带有基类和2个子类的解决方案。基类具有适用于这两个子类的属性,而子类具有仅适用于该特定类的唯一属性。

现在,我有以下问题/问题:在我的基类中有一些私有集属性,并希望稍后在特殊情况下更改它们。我将我的数据存储在类型基类的通用列表中。私有设置后是否可以更改值?

我正在尝试使用反射但无法使其工作。调试时,fieldnull

旁注:我重命名了一些代码来更好地解释我的情况。谢谢你的时间!

CBase test = lstClasses[0];// Assign Class instance from generic list
FieldInfo field = typeof(CBase).GetField( "City", 
    BindingFlags.Instance | BindingFlags.NonPublic
);
field.SetValue(test, "NewCity");

这是基类:

 [Serializable]
public abstract class CBase
{

    //Required flieds

    public string ContactPerson { get; private set; }
    public string Cellnr { get; private set; }
    public string Email { get; private set; }
    public string StreetAdress { get; private set; }
    public string City { get; private set; }
    public string Suburb { get; private set; }
    public DateTime DateAndTime { get; private set; }
    public string TransactionType { get; private set; }
    public bool IsSimple { get; private set; }
    public string EmployeeCode { get; private set; }

    //Optional

    public string Business { get; set; }
    public string Vatnr { get; set; }
    public string Tellnr { get; set; }
    public string PostalAdress { get; set; }
    public string AreaCode { get; set; }

    //Simple Constructor
    public CBase(string _CP, string _Cllnr, string _Eml, string _SrtAdrs
                , string _City, string _Subrb, string _TrnsT
                , bool _IsSimple,DateTime _DateAndTime, string _EmpC)

    {
        ContactPerson = _CP;
        Cellnr = _Cllnr;
        Email = _Eml;
        StreetAdress = _SrtAdrs;
        City = _City;
        Suburb = _Subrb;
        TransactionType = _TrnsT;
        IsSimple = _IsSimple;
        DateAndTime = _DateAndTime;
        EmployeeCode = _EmpC;

    }

    //Full Constructor
    public CBase(string _CP, string _Cllnr, string _Eml, string _SrtAdrs, string
                 _City, string _Subrb, string _TrnsT, string _Buisns
                , string _Tellnr, string _Vatnr, string _PstAd, string _AreaC
                , bool _IsSimple, DateTime _DateAndTime, string _EmpC)

    {
        ContactPerson = _CP;
        Cellnr = _Cllnr;
        Email = _Eml;
        StreetAdress = _SrtAdrs;
        City = _City;
        Suburb = _Subrb;
        DateAndTime = _DateAndTime;
        EmployeeCode = _EmpC;

        Business = _Buisns;
        Vatnr = _Vatnr;
        Tellnr = _Tellnr;
        PostalAdress = _PstAd;
        AreaCode = _AreaC;
        TransactionType = _TrnsT;

        IsSimple = _IsSimple;

    }

0 个答案:

没有答案