Can you restrict type type in general?

I have a dictionary where both keys and values ​​are of type Type, for example ...

private static Dictionary<Type, Type> myDict;

What I'm trying to do is restrict the second Typeonly to types that inherit from FrameworkElement.

Note. I do not tell instances FrameworkElement, I try to store only objects of the type Typethat are inferred from FrameworkElement, making the following statement true ...

var isTypeStorable = typeof(FrameworkElement).IsAssignableFrom(FooType);

So what can this be done?

By the way, I know that I can use the above to verify execution at runtime before adding to the dictionary (which I am doing now). I am wondering if there are any functions in the language that would allow me to limit this at compile time.

+4
source share
2 answers

No , that is impossible. FrameworkElement.GetType()and are FooTypenot related to the type system, both are just Types. If you want to limit your generic type, you will have to do this with runtime checks and exceptions; general constraints will not help you.

If you know what you want to store at compile time (or are happy with some kind of complex reflection), you can change your API to not accept Type, but use the generic code instead:

public void AddTypeForType(Type x, Type y)

can be replaced by

public void AddTypeForType<T1, T2>() where T1 : FrameworkElement
{
    myDict.Add(typeof(T1), typeof(T2));
}

Then you can call it like this:

AddTypeForType<FrameworkDerivedClass, MyCustomClass>();

But this is more of an API change than the answer to your question.

+4
source

, , , , - :

Xx,Yy , myDict SO, , , (inherit from FrameworkElement.)

if(!myDict.ContainsKey(Xx) && /* Yy is inherited from FrameworkElement */)
{
   myDict.Add(Xx,Yy);
}
+1

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


All Articles