相关疑难解决方法(0)

将变量转换为仅在运行时已知的类型?

foreach (var filter in filters)
{
    var filterType = typeof(Filters);
    var method = filterType.GetMethod(filter, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Static);
    if (method != null)
    {
        var parameters = method.GetParameters();
        Type paramType = parameters[0].ParameterType;
        value = (string)method.Invoke(null, new[] { value });
    }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能投valueparamTypevaluestring,paramType很可能只是一个基本的类型一样int,string或者可能float.如果没有可能的转换,我会很好地抛出异常.

c#

75
推荐指数
2
解决办法
7万
查看次数

通过反射设置属性时键入转换问题

我们有一个类型的属性,long?充满了int.

当我直接设置属性obj.Value = v;但是当我尝试通过反射设置属性时,这工作正常,info.SetValue(obj, v, null);它给了我以下异常:

'System.Int32'类型的对象无法转换为'System.Nullable`1 [System.Int64]'类型.

这是一个简化的场景:

    class TestClass
    {
        public long? Value { get; set; }
    }

    [TestMethod]
    public void TestMethod2()
    {
        TestClass obj = new TestClass();
        Type t = obj.GetType();

        PropertyInfo info = t.GetProperty("Value");
        int v = 1;

        // This works
        obj.Value = v;

        // This does not work
        info.SetValue(obj, v, null);
    }
Run Code Online (Sandbox Code Playgroud)

为什么在直接设置属性时设置属性reflection时它不起作用?

c# reflection

25
推荐指数
1
解决办法
4万
查看次数

标签 统计

c# ×2

reflection ×1