C # Generics and the Inheritance Problem

Hey, I would like to know if what I'm trying to do is possible. Comments in the code should give and understand what I'm trying to achieve :)

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

It could be a design issue, and I would be willing to reconsider it if it is :)

+3
source share
2 answers

I would suggest extracting the method DoTestinto a super-interface, for example:

interface ITestable
{
    bool DoTest();
}

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

public class TestTest 
{       
    ITestable myTest;
}

In an unrelated note, it is not recommended that class names begin with "I" and for properties begin with lowercase characters.

+4
source

DoTest() ITest . , ITest t. IEnumerable IEnumerable<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 { ... }
}
0

Source: https://habr.com/ru/post/1764410/


All Articles