已关注 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)
访问 T
的 Type
> 从类(class)内的任何地方。
关于c# - 如何将对象转换为作为参数传递的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47206123/