C# implicit cast “overloading” and reflection problem

瘦欲@ 提交于 2020-01-11 09:51:17

问题


I've got a problem with the following code (which compiles but crashes):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace ConsoleApplication1
{
    public struct MyBoolean
    {
        public bool Value { get; set; }

        //cast string -> MyBoolean
        public static implicit operator MyBoolean(System.String value)
        {
            return new MyBoolean() { Value = (value[0] == 'J') };
        }

        //cast bool -> MyBoolean
        public static implicit operator MyBoolean(bool value)
        {
            return new MyBoolean() { Value = value };
        }

        //cast MyBoolean -> bool
        public static implicit operator bool(MyBoolean value)
        {
            return value.Value;
        }
    }

    public class Foo
    {
        public MyBoolean TestProp { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            MyBoolean myBool = true;        //works

            myBool = "N";   //works

            Foo foo = new Foo();
            foo.TestProp = "J";             //works

            PropertyInfo pi = foo.GetType().GetProperty("TestProp");

            var obj = Convert.ChangeType("J", typeof(MyBoolean));       //throws an InvalidCastException

            pi.SetValue(foo, "J", null);       //throws an ArgumentException

        }
    }
}

I've commented the statements that don't work. Does anyone know why Convert.ChangeType and PropertyInfo.SetValue doesn't seem to use the "overloaded" cast operator as defined in MyBoolean?

Btw, I've been browsing through several other docs here but didn't find an exact match of the problem.

Best regards Thomas


回答1:


Convert.ChangeType() does not use implicit operators. You'll need to have your MyBoolean type implement IConvertible.

The second problem is related. User-defined conversion operators are not used. You'd need to convert it manually before passing it to SetValue().




回答2:


Try implementing IConvertible. Convert casts your instance to that interface in an attempt to perform conversion.

As for PropertyInfo.SetValue, it gets the Set method of the property. When this method is invoked via reflection, AFAICT, the arguments are checked by type rather than the ability to implicitly be cast to the proper type. This cast must be performed before invoking.



来源:https://stackoverflow.com/questions/4501469/c-sharp-implicit-cast-overloading-and-reflection-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!