带有

时间:2016-05-11 18:52:46

标签: c# inheritance

我可以在/*???*/(以及firstclass中的任何其他位置)放置一些东西,使其返回调用它的类的类型,而不会在继承该方法的每个类中覆盖它每次使用时都不会在(secondclass)前加上前缀。什么基本上意味着this.GetType()

public class firstclass
{
    private static /*???*/ current;
    public static /*???*/ modifycurrent()
    {
        /*do stuff to current*/
        return current;
    }
}
public class secondclass : firstclass
{
    //nothing concerning the above
}

//usage
secondclass a = new secondclass();
secondclass b = a.modifycurrent(); //<--no cast here

目标是secondclass的每个实例共享secondclass类型的变量。当我创建继承自firstclass的第三,第四和第五类时,我不必重写所有这些方法(除了返回类型{firstclass之外,它是modifycurrent()中的内容的精确镜像。 {1}}不同)。例如,每种类型的表单都会跟踪先前打开的自身实例。

1 个答案:

答案 0 :(得分:1)

听起来你想要使用奇怪的重复模板模式:

public class firstclass<T> where T:firstclass
{
    private T current;
    public T modifycurrent()
    {
        /*do stuff to current*/
        return current;
    }
}
public class secondclass : firstclass<secondclass>
{
    //nothing concerning the above
}

请注意,我取消了static,因为静态成员不会被继承。

你可以做的不是完全万无一失:

public class thirdclass : firstclass<secondclass>
{
    //nothing concerning the above
}

current仍会返回secondclass的实例。没有任何机制可以强制继承者使用自己的类型作为泛型参数。

相关问题