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)
我怎样才能投value来paramType?value是string,paramType很可能只是一个基本的类型一样int,string或者可能float.如果没有可能的转换,我会很好地抛出异常.
我们有一个类型的属性,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时它不起作用?