简体   繁体   English

从通用类型转换为具体类型的最干净方法

[英]Cleanest way to convert from generic to concrete type

I have a method 我有办法

public Dto Convert<T>(T source)
{
   //todo here?
}

And i need to call the following methods from there based on T, will i have to do TypeOf and switch statement (trying to avoid that)? 我需要从那里基于T调用以下方法,我是否必须执行TypeOf和switch语句(试图避免这种情况)?

public Dto Convert(Contact source) {}
public Dto Convert(Org source) {}
etc...

You could use dynamic : 您可以使用dynamic

public Dto Convert<T>(T source)
{
   var resut = (Dto)Convert((dynamic)source);
}

It will perform method selection at runtime depending on actual source type. 它将在运行时根据实际的source类型执行方法选择。 Will also fail when there is no suitable method with that name available. 如果没有适合该名称的方法,也会失败。

But it seems to be something wrong with your design in general. 但这通常似乎与您的设计有问题。 Are you sure you're not trying to solve XY problem ? 您确定不是要解决XY问题吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM