相关疑难解决方法(0)

如何隐式地反射方法调用

我有一个Thing可以从a中隐式转换的类string.当我Thing直接使用参数调用方法时,正确完成了stringto Thing的强制转换.

但是,如果我使用反射调用相同的方法,它会抛出异常

System.ArgumentException : Object of type 'System.String' cannot be 
converted to type 'Things.Program+Thing'.
Run Code Online (Sandbox Code Playgroud)

也许有充分的理由,但我无法弄明白.有人知道如何使用反射工作吗?

namespace Things
{
    class Program
    {
        public class Thing
        {
            public string Some;

            public static implicit operator Thing(string s)
            {
                return new Thing {Some = s};
            }
        }

        public void showThing(Thing t)
        {
            Console.WriteLine("Some = " + t.Some);
        }

        public void Main()
        {
            showThing("foo");
            MethodInfo showThingReflected = GetType().GetMethod("showThing");
            showThingReflected.Invoke(this, new dynamic[] {"foo"});
        }
    }
} …
Run Code Online (Sandbox Code Playgroud)

.net c# reflection casting implicit-cast

23
推荐指数
2
解决办法
4202
查看次数

反映op_implicit表

我目前正在寻找构建动态类型转换器,

例如,我可以很容易地做到:

public struct Tester
{
    public int Hello;

    public static implicit operator int(Tester d)
    {
        return d.Hello;
    }

    public static implicit operator float(Tester d)
    {
        return d.Hello;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后

typeof(Tester).GetMethods()
Run Code Online (Sandbox Code Playgroud)

将返回我隐式转换MethodInfo.

但是,如果我这样做:

typeof(int).GetMethods()
Run Code Online (Sandbox Code Playgroud)

它不会返回任何op_implicit

我已经看到你可以在这里看到这个表,但我想知道是否有可能从框架本身反映它.

请注意,这不是一个真正的阻塞问题,如果不可能,我会手动从表中添加转换器,但我显然希望动态构建(更干净,更不容易出错).

.net c# reflection

1
推荐指数
1
解决办法
1145
查看次数

标签 统计

.net ×2

c# ×2

reflection ×2

casting ×1

implicit-cast ×1