简体   繁体   English

通用类作为返回类型

[英]Generic class as return type

I have a storage class that uses generics to hold different values. 我有一个使用泛型保存不同值的存储类。

public class Setting<T>
{
    ...
}

In another class I want to make a method like 在另一堂课中,我想做一个像

  public Setting<T> getSetting(string setting)
  {
        return (Setting<T>)settingDictionary[setting];
  }

Where settingDictionary is 在哪里settingDictionary

 private Dictionary<string, object> settingDictionary;

I get error: 我得到错误:

The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?) 找不到类型或名称空间名称“ T”(是否缺少using指令或程序集引用?)

Is there a way to solve this? 有办法解决吗? thanks 谢谢

You need to make the method generic: 您需要使该方法通用:

 public Setting<T> GetSetting<T>(string setting)
 {
   // ... Your code...

Your Setting<T> class doesn't implement Dictionary<string, object> so you should make your method generic type like GetSetting<T> 您的Setting<T>类未实现Dictionary<string, object>因此您应将方法的generic type GetSetting<T>

public Setting<T> GetSetting<T>(string setting)
 {

 }

Here is a DEMO . 这是一个DEMO

好吧,编译器不知道“ T ”是什么,您可以将其定义为通用方法,如下所示:

public Setting<T> getSetting<T>(string setting)

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

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