如何在使用支持对象/结构的泛型时返回空/默认值

本文关键字:泛型 返回 默认值 结构 支持 对象 | 更新日期: 2023-09-27 18:13:04

我正在做一些动态人工智能编程,为了避免为每个用例创建这么多不同的类,以便参数可以正确传递,我认为我会使用一个对象包/容器,类似于字典。

为了支持它完全泛型,我将键作为Type参数,以便我可以在其他项目中使用它,这工作得很好。我的问题是,我想支持对象和结构,所以当涉及到实现TryGet风格的函数时,我不知道如何分配out参数。

这是我的班级:

using System;
using System.Collections.Generic;
namespace mGuv.Collections
{
    public class ObjectBag<TKey>
    {
        private Dictionary<Type, Dictionary<TKey, object>> _objects = new Dictionary<Type, Dictionary<TKey, object>>();
        public ObjectBag()
        {
        }
        private bool HasTypeContainer<T>()
        {
            return _objects.ContainsKey(typeof(T));
        }
        public bool HasKey<T>(TKey key)
        {
            if (HasTypeContainer<T>())
            {
                return _objects[typeof(T)].ContainsKey(key);
            }
            return false;
        }
        public void Add<TIn>(TKey key, TIn value)
        {
            if(!HasTypeContainer<TIn>())
            {
                _objects.Add(typeof(TIn), new Dictionary<TKey, object>());
            }
            _objects[typeof(TIn)].Add(key, value);
        }
        public bool TryGet<TOut>(TKey key, out TOut value)
        {
            if (HasKey<TOut>(key))
            {
                value = (TOut)_objects[typeof(TOut)][key];
                return true;
            }
            // As expected, I can't assign value to null
            value = null; 
            // I also can't just return false as value hasn't been assigned
            return false;
        }
    }
}

是否有办法将值赋给传入的任何默认值?

。我希望能够做到:

ObjectBag<string> myBag = new ObjectBag();
myBag.Add<int>("testInt", 123);
myBag.Add<TestClass>("testClass", new TestClass();
myBag.TryGet<int>("testInt", out someInt);
myBad.TryGet<TestClass>("testClass", out someTestClass);

我不想使用ref,因为这需要在传入变量之前初始化变量

如何在使用支持对象/结构的泛型时返回空/默认值

别介意,我以为default只适用于结构体/值类型。

我可以这样做:

value = default(TOut);
在问问题之前,我真的应该多做研究。我把它留在这里,以防有人像我一样傻。