2010-09-12 106 views
3

嘿,我想知道我想要做甚么可能吗?在代码中的注释应该给和想法是什么,我想才达到:)C#泛型和继承问题

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

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

回答

4

我会建议提取DoTest方法来一个超级接口,就像这样:

interface ITestable 
{ 
    bool DoTest(); 
} 

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

public class TestTest 
{  
    ITestable myTest; 
} 

在一个不相关的音符,故不推荐用于类的名字开始与“我”和性能开始与小写字符。

+2

呀。当你可以称之为'StringTest' /'IntTest'时,也不建议调用'STest' /'ITest',它的可读性会提高一百万倍。 – Timwi 2010-09-12 21:36:00

+0

我不认为特定的命名约定是这里最重要的方面。 – 2010-09-12 21:37:34

+1

@Ondrej:没有人说它是*最重要的。但是,任何使代码更易于理解的代码只会使OP受益。 – 2010-09-12 23:23:26

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 { ... } 
}