问题
Actual call:
ChildClass classCall=new ChildClass();
classCall.FullName="test name";
string returnName=classCall.GetName();
Parent class with method:
public class BaseClass
{
public string GetName()
{
// I can request the value of the property like this.
return this.GetType().GetProperty("FullName")
.GetValue(this, null).ToString();
}
}
Child class:
public partial class ChildClass : BaseClass
{
public string FullName;
public int Marks;
}
Question: How can I avoid hardcoding the property name, i.e. GetProperty("FullName")
. I don't want to hardcode the property name, rather use some other approach and use it in parent method?
回答1:
Firstly, I'd suggest avoiding using public fields - use properties if you want to make state public. (You're asking for a property in your reflection call, but your derived class declares a field...)
At that point, you can make FullName
an abstract property in the base class, and allow each derived class to implement it however they want - but you can still call it from the base class.
On the other hand, if every derived class is going to have to implement it, why not just pass it into the base class's constructor? Either the class makes sense without a FullName
or it doesn't - your current code will break if there isn't a FullName
field, so why not have it in the base class to start with?
回答2:
public class BaseClass
{
public virtual string GetName()
{
return string.Empty;
}
}
public partial class ChildClass : BaseClass
{
public string FullName;
public int Marks;
public override string GetName()
{
return FullName;
}
}
However, if you never want to initialize a BaseClass object you want to make it abstract and force everybody who implements it to implement its own version of the GetName method:
public abstract class BaseClass
{
public abstract string GetName();
}
BR
来源:https://stackoverflow.com/questions/27023200/call-method-from-a-parent-class-and-use-child-class-properties