将返回值转换为通用类型 [英] Casting return value to a generic type

查看:64
本文介绍了将返回值转换为通用类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个具有单个通用方法的接口:

Suppose we have an interface with a single generic method:

public interface IExtender
{
    T GetValue<T>(string tag);
}

和它的一个简单实现A,根据"tag"参数返回两种不同类型(B和C)的实例:

and a simple implementation A of it that returns instances of two different types (B and C) depending on the "tag" parameter:

public class A : IExtender
{
    public T GetValue<T>(string tag)
    {
        if (typeof(T) == typeof(B) && tag == null)
            return (T)(object) new B();
        if (typeof(T) == typeof(C) && tag == "foo")
            return (T)(object) new C();
        return default(T);
    }
}

是否可以避免重复使用(T)(object)?或者,有没有办法告诉编译器嘿,我敢肯定,这种强制转换不会在运行时失败,只要让我先执行强制转换即可!"

is it possible to avoid the double cast (T)(object)? Or, is there a way to tell the compiler "hey, I am sure that this cast won't fail at runtime, just let me do it without first casting to object!"

推荐答案

或者,有没有办法告诉编译器嘿,我敢肯定,这个强制转换不会在运行时失败,只要让我先执行强制转换即可!"

Or, is there a way to tell the compiler "hey, I am sure that this cast won't fail at runtime, just let me do it without first casting to object!"

不,该语言是故意设计的,以防止出现这种情况.埃里克·利珀特(Eric Lippert)最近关于此的博客.我同意这很烦人,但确实有一定道理.

No, the language is deliberately designed to prevent this. Eric Lippert blogged about this recently. I agree it's annoying, but it does make a certain kind of sense.

说实话,这样的通用"方法通常 有点设计味道.如果某个方法必须具有针对各种不同类型的特殊情况,则至少应考虑使用单独的方法.( GetB GetC )

To be honest, "generic" methods like this are usually a bit of a design smell. If a method has to have special cases for various different types, you should at least consider using separate methods instead. (GetB, GetC)

这篇关于将返回值转换为通用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆