C# 泛型和继承问题

3

嘿,我想知道我正在尝试做的事情是否可能?代码中的注释应该能够说明我要实现的目标 :)

interface ITest<T> {
    T t { get; }
    bool DoTest();
}

public abstract class Test<T> : ITest<T> {
    public Test (T nt) {
        this.t = nt;
    }

    public Test () {
    }

    public T t {
        get;
        private set;
    }

    public abstract bool DoTest ();
}

public class STest : Test<string> {
    public override bool DoTest () {
    return true;
    }
}

public class ITest : Test<int> {
    public override bool DoTest () {
        return true;
    }
}

public class TestTest {
    // I don't want to specify type here, I'd like TestTest to be able to have
    // either a ITest or a STest. But for this class it should not matter.
    // I just want to use DoTest() later on. No matter what 
    // specialication of Test this is.
    Test myTest;
}

这可能是一个设计问题,如果是的话,我愿意重新考虑 :)
2个回答

4
我建议将DoTest方法提取到一个超级接口中,如下所示:
interface ITestable
{
    bool DoTest();
}

interface ITest<T> : ITestable
{
    T t { get; }
}

public class TestTest 
{       
    ITestable myTest;
}

顺便提一下,不建议使用'I'开头作为类名,也不建议属性以小写字母开头。


2
是的。当你可以叫它StringTest/IntTest并且这样会更容易阅读时,也不建议将其称为STest/ITest - Timwi
我认为特定的命名约定并不是最重要的方面。 - Ondrej Tucny
1
@Ondrej:没有人说这是 重要的。但是,任何使代码更易于理解的东西都只有益处对OP。 - Steven Sudit

0
DoTest()方法放置在非泛型的ITest接口中。此外,我建议使ITest接口具有t的非泛型版本。这是一种常见的方法,就像IEnumerableIEnumerable<T>接口一样。优点是非泛型版本不会变得更少功能,因此可以在无法提供实际类型参数的地方充分利用它。
interface ITest
{
    object t { get; }
    bool DoTest();
}

interface ITest<T> : ITest
{
    T t { get; }
}

由于显式实现,不需要的非泛型或泛型版本(取决于实际情况)可以被隐藏:
class STest : ITest<S>
{
    public string t { get; private set; }
    string ITest.t { get { return t; } }
    public bool DoTest { ... }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接