I have a (hopefully) simple question:
I have some classes:
class Foo
class Foo1 : Foo
class Foo2 : Foo
I have two dictionaries:
Dictionary<int, Foo1> dic1
Dictionary<int, Foo2> dic2
And I have a method:
private static int Method(Dictionary<int, Foo>)
and a method call:
Method(dic1);
but now I get the error that I can't convert Dictionary<int, Foo1>
to Dictionary<int, Foo>
.
How do I solve this problem?
Thank you :)
In Python, you can do this by inheriting from an abstract base class, by subclassing the built-in dict class directly, or by inheriting from UserDict . In this tutorial, you'll learn how to: Create dictionary-like classes by inheriting from the built-in dict class.
The __dict__ in Python represents a dictionary or any mapping object that is used to store the attributes of the object. They are also known as mappingproxy objects. To put it simply, every object in Python has an attribute that is denoted by __dict__.
Although classes can inherit only one class, they can implement multiple interfaces.
Yes, they can be inherited.
Generics, with a constraint of Foo
should do it
public class Foo { }
public class Foo1 : Foo { }
public class Foo2 : Foo { }
public class SomeClass
{
public static int Method<T>(Dictionary<int, T> dict) where T : Foo
{
...
}
}
Additional Resources
Constraints on type parameters (C# Programming Guide)
Constraints inform the compiler about the capabilities a type argument must have. Without any constraints, the type argument could be any type. The compiler can only assume the members of Object, which is the ultimate base class for any .NET type.
...
By constraining the type parameter, you increase the number of allowable operations and method calls to those supported by the constraining type and all types in its inheritance hierarchy. When you design generic classes or methods, if you will be performing any operation on the generic members beyond simple assignment or calling any methods not supported by System.Object, you will have to apply constraints to the type parameter.
...
For example, the base class constraint tells the compiler that only objects of this type or derived from this type will be used as type arguments. Once the compiler has this guarantee, it can allow methods of that type to be called in the generic class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With