可以返回不同类型的通用方法 [英] Generic method that can return different types

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

问题描述

我有一个基本的抽象类,该类旨在允许实现者返回不同的类型:

I have a base abstract class which is meant to allow implementors to return different types:

protected abstract T GetMyValue<T>();

我希望实现类能够执行以下操作:

I would like the implementing class to be able to do something like this:

T myResult;    
public override T GetMyValue<T>()
{

     return _myResult;
}

我希望呼叫者指定类型:

I would like the caller to specify the type:

int i = obj.GetMyValue<int>();

这可能吗?

推荐答案

一种选择就是将字段存储为对象.这将导致对结构进行装箱,但是没有更重要的更改,没有更好的方法.

One option would just be to store the field as an object. This will cause boxing for structs, but there isn't better way without a more significant change.

class Derived : Base
{
     private object o;

     protected override T GetMyValue<T>()
     {
        if (o is T)
           return (T)o;

        return default(T);
     }
}

除非抽象类本身是通用的,而不是特定的方法,否则您实际上不能拥有通用的字段.当然,这是一个重大的设计更改.现在,一种实现只能返回一种类型.像

You can't really have a generic field unless the abstract class is itself generic, not the specific method. Of course this is a significant design change. One implementation can now only return one type. Something like

abstract class BaseClass<T>
{
    protected abstract T GetMyValue();
}

class Derived : Base<int>
{
    private int i;

    protected override int GetMyValue()
    {
        return i;
    }
}

这篇关于可以返回不同类型的通用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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