c# - 如何从反射执行显式操作转换?

标签 c# operators implicit-conversion explicit-conversion

我想使用反射并使用反射进行隐式或显式覆盖。

鉴于我已经这样定义了 Foo

public class Foo
{
    public static explicit operator decimal(Foo foo)
    {
        return foo.Value;
    }

    public static explicit operator Foo(decimal number)
    {
        return new Foo(number);
    }

    public Foo() { }

    public Foo(decimal number)
    {
        Value = number;
    }

    public decimal Value { get; set; }

    public override string ToString()
    {
        return Value.ToString();
    }
}

当我运行这段代码时

decimal someNumber = 42.42m;

var test = (Foo)someNumber;

Console.WriteLine(test);        // Writes 42.42 No problems

当我尝试定义一个以 Foo 作为成员类型的类并使用反射来设置它时。我得到以下异常。

Error     : Object of type 'System.Decimal' cannot be converted to type 'Foo'.
StackTrace:    at System.RuntimeType.TryChangeType(Object value, Binder binder, CultureInfo culture, Boolean needsSpecialCast)
               at System.RuntimeType.CheckValue(Object value, Binder binder, CultureInfo culture, BindingFlags invokeAttr)
               at System.Reflection.MethodBase.CheckArguments(Object[] parameters, Binder binder, BindingFlags invokeAttr, CultureInfo culture, Signature sig)
               at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
               at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
               at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
               at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, Object[] index)

这是我用反射设置属性的代码

public class FooComposite
{
    public Foo Bar { get; set; }
}

var properties = typeof(FooComposite).GetProperties();

var testFoo = new FooComposite();

foreach(var propertyInfo in properties)
{
    propertyInfo.SetValue(testFoo, 17.17m, null);  // Exception generated on this line
}

Console.WriteLine(testFoo.Bar);  // Never gets here

我怎样才能进行这种转换?

最佳答案

嗯,它与非反射代码没有什么不同,您仍然需要将数字显式转换为 Foo:

propertyInfo.SetValue(testFoo,(Foo)17.17m, null);

实例:http://rextester.com/rundotnet?code=BPQ74480

出于兴趣,我尝试了一些替代方案。

  1. 让它成为Foo 中的隐式 转换 - 不起作用,同样的错误 Live
  2. 使用 Convert.ChangeType(17.17m,typeof(Foo)) - 也不起作用。 Live

关于c# - 如何从反射执行显式操作转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7351289/

相关文章:

c# - Graph API 拒绝访问,即使我授予了访问权限

C++ 流和运算符 >> 优先级

scala - 对此的隐式转换没有启动

c++ - 三路运算符 <=> 返回带有隐式转换函数的结构体

C++ 从 const char 到 string 的自动隐式转换

c# - 如何将 IdentityRole 扩展为自定义表名

c# - SQL 语句转换为 LinQ 语句

javascript - 没有在另一个页面上获取 c# webmethod json 字符串

c++ - operator++ 作为后缀和前缀都不适用于 clang

sql - AND/OR 运算符未按需要进行过滤