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

标签 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
     }
}

最佳答案

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

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,因为您可以使用 typeof(T) 访问 TType > 从类(class)内的任何地方。

关于c# - 如何将对象转换为作为参数传递的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47206123/

相关文章:

c# - 切换 UInt64 和 uint

arrays - Ada 中无约束可变类型的数组

javascript - 将多个参数从 ASP.NET 传递到 JavaScript 函数

c# - 如何从 Global asax 中访问 UrlHelper.Action 或类似的

c# - Dapper.SimpleCRUD 没有标识的插入问题

arrays - 创建通用多路复用器

循环引用特征的 Scala 类型错误

C 函数参数

c - 传递给 C 函数时丢失 char 数组的值

c# - 将 XML 数据读入 C# 应用程序