繁体   English   中英

我可以调用基于 class 的 static 方法,并参考实现该基础 ZA2F2ED4F8EBC2CBB4C21 的 class 吗?

[英]Can I call a static method that lives on a base class with a reference the the class implementing that base class (in C#)?

我很难说出这个问题,这也让我很难寻找答案。

这是一个模仿我想做的人为场景:

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;
    }
}

控制台现在会显示:

Name
OtherPropertyName

我想替换我注释掉的代码,这样它就会变成:

Name
OtherPropertyName
Name
OtherPropertyName

如果您将 Writeline 更改为

Console.WriteLine(BaseClass<T>.MyPropertyName());

你会得到你想要的

为什么在基础 class 中使用 static function 来检索有关派生 ZA2F2ED4F8EBC2CBB4DC21A29 的信息? 在任何情况下,您都可以实现成员 function 来包装 static 调用:

public static string MyStaticFunction() => return "whatever";

public string MyMemberFunction() => MyStaticFunction();

但是在您的场景中,也许您应该简单地声明一个抽象属性(或函数),以返回您正在寻找的值并在派生类中覆盖它:

根据:

public abstract string MyPropertyName { get; }

衍生的:

public override string MyPropertyName => nameof(OtherPropertyName); // or more complex logic

另一种可能的解决方案是将信息作为字符串传递给基类的构造函数(或属性表达式,如果您愿意的话):

根据:

public string MyPropertyName { get; init; }

public BaseClass(string propertyName)
{
    MyPropertyName = propertyName; // maybe validate that the property exists
}

衍生的:

public MyTestClassB() : BaseClass(nameof(OtherPropertyName)) {}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM