[英]Can I call a static method that lives on a base class with a reference the the class implementing that base class (in C#)?
I'm having a hard time phrasing the question which is also making it hard for me to search for answers.我很难说出这个问题,这也让我很难寻找答案。
Here's a contrived scenario that mimics what I'd like to do:这是一个模仿我想做的人为场景:
void Main()
{
Console.WriteLine(TestClassA.MyPropertyName());
Console.WriteLine(TestClassB.MyPropertyName());
var speaker = new TestSpeaker();
speaker.Speak<TestClassA>();
speaker.Speak<TestClassB>();
}
public class TestSpeaker {
public void Speak<T>() where T : BaseClass<T> {
Console.WriteLine(/* I want to call T.MyPropertyName() here */);
}
}
public class TestClassA : BaseClass<TestClassA> {
public string Name { get; set; }
}
public class TestClassB : BaseClass<TestClassB> {
public string OtherPropertyName { get; set; }
}
public abstract class BaseClass<T> {
public static string MyPropertyName(){
return typeof(T).GetProperties().Single().Name;
}
}
The Console right now would read:控制台现在会显示:
Name
OtherPropertyName
I'd like to replace my commented out code so that it would read:我想替换我注释掉的代码,这样它就会变成:
Name
OtherPropertyName
Name
OtherPropertyName
if you change your Writeline to如果您将 Writeline 更改为
Console.WriteLine(BaseClass<T>.MyPropertyName());
you will get what you want你会得到你想要的
Why use a static function in a base class to retrieve information about a derived class?为什么在基础 class 中使用 static function 来检索有关派生 ZA2F2ED4F8EBC2CBB4DC21A29 的信息? In any case, you could implement a member function to wrap the static call:在任何情况下,您都可以实现成员 function 来包装 static 调用:
public static string MyStaticFunction() => return "whatever";
public string MyMemberFunction() => MyStaticFunction();
But in your scenario, perhaps you should simply declare an abstract property (or function) meant to return the value you're looking for and override it in derived classes:但是在您的场景中,也许您应该简单地声明一个抽象属性(或函数),以返回您正在寻找的值并在派生类中覆盖它:
Base:根据:
public abstract string MyPropertyName { get; }
Derived:衍生的:
public override string MyPropertyName => nameof(OtherPropertyName); // or more complex logic
And yet another possible solution would be to pass the information to the base class's constructor as a string (or property expression should you be so inclined):另一种可能的解决方案是将信息作为字符串传递给基类的构造函数(或属性表达式,如果您愿意的话):
Base:根据:
public string MyPropertyName { get; init; }
public BaseClass(string propertyName)
{
MyPropertyName = propertyName; // maybe validate that the property exists
}
Derived:衍生的:
public MyTestClassB() : BaseClass(nameof(OtherPropertyName)) {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.