将Type转换为myType

时间:2017-02-20 17:40:54

标签: c# reflection types casting

我想为decimal中的所有Object字段设置默认值。这样做的方法如下:

private Type SetAllFieldsAsDefault(Type register)
{
    var fields = register.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
    foreach (var field in fields)
    {
        if (field.FieldType != typeof(double)) continue;
        field.SetValue(field, 0);
    }
    return register;
}

我尝试转换为myType后,但它不起作用

myType = (MyType )SetAllFieldsAsDefault(myType.GetType());

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您需要一个对象作为输入和输出

 private object SetAllFieldsAsDefault(object _register)
 {
      Type register = _register.GetType();

并且您将在上述方法中设置其值

      field.SetValue(_register, 0);

最后链接修改后的输入

return _register;
}

调用方法

myType = (MyType)SetAllFieldsAsDefault(myType);

这是test online

public static void Main()
{
    var myType = new MyType();
    Console.WriteLine(myType.one + " " + myType.two);
    Console.WriteLine("before");
    myType = SetAllFieldsAsDefault(myType) as MyType;
    Console.WriteLine("after");
    Console.WriteLine(myType.one + " " + myType.two);
}

class MyType {
    internal double one = -1.1;
    internal string test = "hi";
    internal double two = 3.3;
}

输出

before
-1.1 3.3
after
0 0