在C#中将通用类型参数转换为特定类型

编程入门 行业动态 更新时间:2024-10-19 16:40:47
本文介绍了在C#中将通用类型参数转换为特定类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如果您需要将泛型类型参数转换为特定类型,我们可以将其转换为对象并进行如下转换,

If you need to cast a generic type parameter to a specific type we can cast it to a object and do the casting like below,

void SomeMethod(T t) { SomeClass obj2 = (SomeClass)(object)t; }

有没有比将其强制转换为对象然后再转换为特定类型更好的方法了?

Is there a better way to achieve this rather than casting it to a object and then to a specific type.

问题

我有一个接受泛型类型参数的泛型函数,在函数内部基于类型检查,我进行了如下操作

I have a generic function which accepts a generic type parameter, inside the function based on a type checking I do some operations like below

void SomeMethod(T t) { if (typeof(T).Equals(typeof(TypeA))) { TypeA = (TypeA)(object)t; //Do some operation } else if (typeof(T).Equals(typeof(TypeB))) { TypeB = (TypeB)(object)t; //Do some operation } }

推荐答案

一个更好的设计是在类型T和您希望在方法中使用的类(在本例中为SomeClass)之间施加约束.

A better design is to put a constraint on it that is common between type T and the class you want to expect in your method, in this case SomeClass.

class SomeConsumer<T> where T : ISomeClass { void SomeMethod(T t) { ISomeClass obj2 = (ISomeClass) t; } } interface ISomeClass{} class SomeClass : ISomeClass {}

基于问题的编辑进行编辑

那是糟糕的设计.尝试将操作"移到类本身中,以便调用者不必知道类型.如果这不可能实现,请分享更多正在执行的操作,但是您想要完成的是您没有一堆if/else语句,其执行取决于要传递给该方法的对象的类型.

Edit based on edit of Question

That is bad design. Try to move that "operation" into the class itself so the caller does not have to know the type. If that is not possible share more of what is being done, what you want to accomplish though is that you do not have a stack of if/else statements where execution depends on the type of object being passed in to the method.

class SomeConsumer<T> where T : ISomeClass { void SomeMethod(T t) { ISomeClass obj2 = (ISomeClass) t; // execute t.Operation(); } } interface ISomeClass{ void Operation(); } class SomeClass : ISomeClass { public void Operation(){/*execute operation*/} }

更多推荐

在C#中将通用类型参数转换为特定类型

本文发布于:2023-11-11 23:16:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1579812.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   转换为   中将   参数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!