我有一个基类和 2 个子类的解决方案,基类具有适用于两个子类的属性,子类具有仅适用于该特定类的唯一属性。
现在,我有以下问题/疑问:在我的基类中有一些私有设置属性,并且希望稍后在特殊情况下更改它们。我将数据存储在类型基类的通用列表中。私有设置后是否可以更改值?
我正在尝试使用反射,但无法使其正常工作。调试时它会出现因为field
is null
。
旁注:我重命名了一些代码以更好地解释我的情况。感谢您的时间!
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;
}