Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've got two generic base classes. The second generic class has a constraint on its parameter of the first class.

abstract class FirstClass<T> {...}

abstract class SecondClass<U> where U : FirstClass {...}

This does not work, because FirstClass is not defined. So I need to do this.

abstract class FirstClass<T> {...}

abstract class SecondClass<U, T> where U : FirstClass<T> {...}

Which works. However, this makes implementing these abstract classes ugly.

class SomeClass {...}

class MyFirstClass : FirstClass<SomeClass> {...}

class MySecondClass : SecondClass<MyFirstClass, SomeClass> {...}

This seems redundant to me because I'm specifying SomeClass twice. Is there a way to declare it in such a way that T from FirstClass is automatically the U for SecondClass. What I would really like this to look like is.

class SomeClass {...}

class MyFirstClass : FirstClass<SomeClass> {...}

class MySecondClass : SecondClass<MyFirstClass> {...}

While I doubt this exact scenario is possible, is there a cleaner what to do what I am trying to do?

Edit

Several people have suggested making an IFirstClass interface. But my definitions are closer to this.

class FirstClass<T>
{
    public T MyObj { get; set; }
}

class SecondClass<U, T> where U : FirstClass<T>
{
    U MyFirstClass { get; set; }
}

With an interface I cannot access MyFirstClass.MyObj from SecondClass. While I could create a object T MyObj { get; set; } on IFirstClass, then use new to hide it, silverlight throws a fit in the binding if I do this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
328 views
Welcome To Ask or Share your Answers For Others

1 Answer

In my experience it is easiest to create non-generic interface to generic classes. It also solves the problem when you need to cast to the base class without knowing the generic type.

interface IFirstClass {...}

abstract class FirstClass<T> : IFirstClass {...}

abstract class SecondClass<T> where T : IFirstClass {...}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...