开发者

C# implicit cast "overloading" and reflection problem

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


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().


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜