Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

c# - Generics with Generic Parameters and Abstract class

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...