实际上,我想在方法中访问基类的属性,而不是直接实例化该对象。下面是代码,我正在研究:
public class Test
{
public static void Main()
{
drivedclass obj = new drivedclass();
obj.DoSomething();
}
}
public class drivedclass : baseclass
{
public void DoSomething()
{
LoadSomeThing();
}
}
public class baseclass
{
public string property1
{
get;
set;
}
public string property2
{
get;
set;
}
public void LoadSomeThing()
{
//here I want to access values of all properties
}
}
我想知道是否有办法,我可以访问同一类方法中的属性,该类是基类。
答案 0 :(得分:2)
您可以按原样使用property1
和property2
。
但请注意,在LoadSomeThing()
中,您将无法访问drivedlcass
的任何属性,因为基类根据定义无法查看其派生类的属性。
答案 1 :(得分:1)
您可以使用反射访问它们,但这不是“正常”方式。
foreach(PropertyInfo prop in this.GetType().GetProperties())
{
prop.SetValue(this, newValue);
}
如果你想让它更“干净”,你应该把属性变成虚拟的。
答案 2 :(得分:1)
使用以下方法枚举所有属性值:
public void EnumerateProperties()
{
var propertiesInfo = this.GetType().GetProperties();
foreach (var propertyInfo in propertiesInfo)
{
var val = propertyInfo.GetValue(this, null);
}
}
答案 3 :(得分:0)
问题很安静,但是如果你想访问你的属性,它们在Base类和派生类中都很好。因此,如果你在主类Test中s = obj.property2
,那应该是可用的。
public class Test {
public static void Main( ) {
drivedclass obj = new drivedclass( );
obj.DoSomething( );
string s = obj.property2 ;
}
}
答案 4 :(得分:0)
您可以随时明确指出:
public class DerivedClass : BaseClass
{
public string Property3
{ get; set; }
public void DoSomething ()
{
LoadSomeThing();
}
public override void LoadSomeThing ()
{
base.LoadSomeThing();
Console.WriteLine(Property3);
}
}
public class BaseClass {
public string Property1
{ get; set; }
public string Property2
{ get; set; }
public virtual void LoadSomeThing()
{
Console.WriteLine(Property1);
Console.WriteLine(Property2);
}
}
答案 5 :(得分:0)
您可以尝试:this.property1