如何将对象转换为作为参数传递的类型

时间:2017-11-09 15:50:21

标签: c# types parameters casting

关注this question,我发现可以将类型传递给方法。在传递类型的方法内部,如何将对象强制转换为传递的类型?作为一个复杂因素,类Foo继承自我无法改变的类。

 var x = FetchData();
 Foo foo = new Foo(2, typeof(Gizmo));   // pass the Gizmo type
 foo.Execute(x);


public class Foo :  ThirdPartyLibrary.Operation
{
    Type customtype;


     public Foo(int i, Type passedtype)  : base()
     {
          this.customtype=passedtype;
     }

     public override void Execute(ThirdPartyLibrary.Node node)
     {
         var record = ( ??? ) node.GetData();     // cast node to the type of customtype
     }
}

1 个答案:

答案 0 :(得分:2)

如果我正确理解您的问题,您可以使用泛型来完成此操作。它看起来像这样(基于你的示例代码):

public class Foo<T> : ThirdPartyLibrary.Operation
{
    public Foo(int i) : base()
    {
         //hopefully you actually do something useful with "i" here.
    }

    public override void Execute(ThirdPartyLibrary.Node node)
    {
        //I'm not 100% sure which object you are trying to cast, so I'm showing both forms below.  You obviously won't be able to do both without changing the variable name.

        //If you want to cast the "Data", use this.
        var record = (T) node.GetData();

        //If you want to cast "node", use this.
        var record = ((T) node).GetData();
    }
}

你这样使用它:

var x = FetchData();
Foo foo = new Foo<Gizmo>(2); 
foo.Execute(x);

customtype不再需要,因为您可以从班级中的任何位置访问Type T typeof(T)