C # Equivalent to Java GenericType <?>

I work with some generics in C #. I have an abstract generic class:

public abstract class BaseClass<T> where T : Foo { } 

and the type parameter is specified when other classes inherit from the base class.

I am also trying to write code for another abstract class that should store one of these base classes, but it will not know the base class parameter (and it does not need to know). In Java, I could just write:

 protected BaseClass<?> myBaseClass; 

But in C #, he insists that I give him a type parameter. If I declare it as:

 protected BaseClass<Foo> myBaseClass; 

I cannot assign parameterized BaseClass values ​​to BaseClass .

Is there any work to achieve the BaseClass<?> Effect in C #? Obviously, there are ways to restructure my code to avoid the need, for example, parameterizing all classes that use BaseClass , but that would be less than ideal. Any help would be appreciated!

+6
source share
3 answers

To map Java behavior in C #, an additional non-generic interface is usually added to the inheritance hierarchy.

 public interface IBaseClass { Foo GetValue(); void SetValue(Foo value); } public abstract class BaseClass<T> : IBaseClass where T : Foo { public T GetValue<T>() { /* ... */ } public void SetValue<T>(T value) { /* ... */ } Foo IBaseClass.GetValue() // Explicit interface method implementation { return (Foo)GetValue<T>(); } void IBaseClass.SetValue(Foo value) // Explicit interface method impl. { SetValue<T>((T)value); } } 

And then use IBaseClass where you need BaseClass<?> :

 IBaseClass myClass; Foo f = myClass.GetValue(); 
+2
source

Classes using this type must also be generic if you do not already know the general argument of this class.

0
source

If you use a wildcard in the parameter declaration for a method, you need to make a generic method:

 void printBaseClass<T>(BaseClass<T> o) where T : Foo { // ... } 

If you use this as a variable type declaration, just use var .

 var o = GetBaseClassOfSomeType(); 
0
source

All Articles