加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 是否可以在字典中存储Func?

发布时间:2020-12-15 08:32:24 所属栏目:百科 来源:网络整理
导读:我希望能够使用Type的键和Func T的值来实现字典.其中T是与键相同类型的对象: DictionaryType,FuncT TypeDictionary = new DictionaryType,FuncT( ) /*FuncT returns an object of the same type as the Key*/TypeDictionary.Add( typeof( int ),( ) = 5 );T
我希望能够使用Type的键和Func< T>的值来实现字典.其中T是与键相同类型的对象:
Dictionary<Type,Func<T>> TypeDictionary = new Dictionary<Type,Func<T>>( ) /*Func<T> returns an object of the same type as the Key*/

TypeDictionary.Add( typeof( int ),( ) => 5 );
TypeDictionary.Add( typeof( string ),( ) => "Foo" );

因此,基本上,字典将填充有引用Func< T>的类型.哪会返回该值:

int Bar = TypeDictionary[ typeof( int ) ]( );
string Baz = TypeDictionary[ typeof( string ) ]( );

我该如何实施和执行此操作?

解决方法

这差不多就像你要得到的那样:
void Main()
{
    var myDict = new MyWrappedDictionary();
    myDict.Add(() => "Rob");
    var func = myDict.Get<string>();
    Console.WriteLine(func());
}

public class MyWrappedDictionary
{
    private Dictionary<Type,object> innerDictionary = new Dictionary<Type,object>();
    public void Add<T>(Func<T> func)
    {
        innerDictionary.Add(typeof(T),func);
    }
    public Func<T> Get<T>()
    {
        return innerDictionary[typeof(T)] as Func<T>;
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读