C#隐式转换"超载"和反思的问题 [英] 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
}
}
}
我评论说,不工作的陈述。有谁知道为什么似乎Convert.ChangeType和PropertyInfo.SetValue没有使用重载剧组运营商在MyBoolean界定?
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()
不使用隐式操作。你需要让你的MyBoolean类型实施 IConvertible
。
Convert.ChangeType()
does not use implicit operators. You'll need to have your MyBoolean type implement IConvertible
.
第二个问题是有关。用户自定义转换操作不会被使用。你需要它,它传递给的SetValue()
之前手动转换。
The second problem is related. User-defined conversion operators are not used. You'd need to convert it manually before passing it to SetValue()
.
这篇关于C#隐式转换"超载"和反思的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!