C# 当使用支持对象/结构的泛型时,如何返回null/默认值?
我正在做一些动态人工智能编程,为了避免为每个用例创建这么多不同的类,以便能够正确地传递参数,我想我应该使用一个类似于字典的对象包/容器 为了支持它的完全通用性,我将键设置为一个类型参数,这样我就可以在其他项目中使用它,这很好。我的问题是,我想支持对象和结构,所以在实现C# 当使用支持对象/结构的泛型时,如何返回null/默认值?,c#,generics,C#,Generics,我正在做一些动态人工智能编程,为了避免为每个用例创建这么多不同的类,以便能够正确地传递参数,我想我应该使用一个类似于字典的对象包/容器 为了支持它的完全通用性,我将键设置为一个类型参数,这样我就可以在其他项目中使用它,这很好。我的问题是,我想支持对象和结构,所以在实现TryGet风格的函数时,我不知道如何分配out参数 这是我的班级: using System; using System.Collections.Generic; namespace mGuv.Collections {
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;
}
}
}
使用系统;
使用System.Collections.Generic;
命名空间mGuv.Collections
{
公共类对象包
{
私有字典_objects=新字典();
公共物品袋()
{
}
私有bool hastype容器()
{
返回_objects.ContainsKey(typeof(T));
}
公共bool HasKey(TKey)
{
if(HasTypeContainer())
{
返回_objects[typeof(T)]。ContainsKey(key);
}
返回false;
}
公共无效添加(TKey、TIn值)
{
如果(!HasTypeContainer())
{
_Add(typeof(TIn),newdictionary());
}
_对象[类型(TIn)]。添加(键、值);
}
公用bool TryGet(TKey、out TOut值)
{
if(HasKey(key))
{
value=(TOut)u对象[typeof(TOut)][key];
返回true;
}
//正如预期的那样,我不能将值赋给null
值=空;
//我也不能只返回false,因为还没有赋值
返回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);
ObjectBag myBag=newobjectbag();
myBag.Add(“testInt”,123);
Add(“testClass”,newtestclass();
myBag.TryGet(“testInt”,out someInt);
TryGet(“testClass”,out someTestClass);
我不想使用ref,因为这需要在传入变量之前初始化它。不过,我认为
default
只适用于结构/值类型
我可以做到:
value = default(TOut);
在问问题之前,我真的应该做更多的研究。我会把它留给别人,以防其他人像我一样愚蠢。你可以用。@Verarind,是的,你是对的,谢谢。出于某种原因,我认为
default
只处理值类型。