开发者

Generic wrapper and isAssignableFrom not working

开发者 https://www.devze.com 2023-01-29 12:28 出处:网络
I am trying to create a generic wrapper that wraps all kind of value an supplies some extra functions.

I am trying to create a generic wrapper that wraps all kind of value an supplies some extra functions.

The wrapper looks like:

 class PropertyWrapper<T>
{
    private T _value;

    public PropertyWrapper(T value)
    {
        _value = value;
    }

    public PropertyWrapper()
    {
    }

    public static implicit operator T(PropertyWrapper<T> value)
    {
        return value._value;
    }

    public static implicit operator PropertyWrapper<T>(T value)
    {
        return new PropertyWrapper<T>(value);
    }

}

It has the implicit converter operator so that the programmer can work with it like he is working with the wrapped type.

Now I have the following code:

        PropertyWrapper<Int32> wrapped = new PropertyWrapper<Int32>();
        Int32 unwrapped;

        unwrapped = 42;

        wrapped = unwrapped; //working

        wrapped = 21; //working

        unwrapped = wrapped; //working

        if (wrapped.GetType().IsAssignableFrom(unwrapped.GetType())) //will return false.
        {
            foo();
        }

Now i see that the function IsAssignableFrom working right, because it only tells if you can assign to the variable directly without any type conversion. Is there anyway to modify the Wrapper Class to work around this? As the primitive types on CLR (aka struct) do not allow to inherit from I have no clue how to manage that. Any ideas on that?

Tha开发者_Go百科nks in Advance.


As SLaks points out, user-defined conversions don't play well with this sort of reflection. But it's not clear from your sample why you need to do this. If you just want to test if the wrapped type could potentially wrap the unwrapped type, you could just do:

var wrappedUnderlyingType = wrapped.GetType().GetGenericArguments().Single();

if (wrappedUnderlyingType.IsAssignableFrom(unwrapped.GetType()))
{
   foo();
}

If you could give us more information about why you want to perform this sort of reflection, and how the code should proceed if the test succeeds, we might be able to help more.


User-defined cast operators are normal static methods with special names.
The CLR, unlike the C# compiler, will not attach any significance to them.

I don't think you'll be able to do this.
You can try this trick, but I'm not sure whether it will work.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号