c# - 如何在字典中制作通用 Func<T>

标签 c# .net generics

是否可以制作

public class MyClass : Dictionary<string, Func<string>>

作为

public class MyClass : Dictionary<string, Func<T>>

其实我有

public class MyClass : Dictionary<string, Func<string>>
{
    public void MyFunction(string key)
    {
        if (this.ContainsKey(key))
            this[key]();
        else
            this["no match"]();
    }
}

我想将值设置为通用值。可能吗?

谢谢。

最佳答案

必须在某处指定类型,因此您还必须使您的类通用:

public class Myclass<T> : Dictionary<string, Func<T>> {

  public T MyFunction(string key) {
    if (this.ContainsKey(key)) {
      return this[key]();
    } else {
      return this["no match"]();
    }
  }

}

关于c# - 如何在字典中制作通用 Func<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5700069/

相关文章:

C# 获取 T 属性的类型

c# - Windows 服务不正确的功能

c# - 在 C# 中的单色位图上绘制文本

.net - 在 Visual Studio 中发布网站 : Use 'Fixed naming and single page assemblies' ?

java - 特定类到 Collection 对象的数组?

java - Eclipse 中的有限不匹配。 "The type is not a valid substitute for the bounded parameter"

generics - 如何调用泛型重载方法

c# - 捕获不同线程引起的异常

c# - 获取 foreach 循环中的最后一项

c# - WebApi 2 不使用域模型 Dbcontext 连接字符串