gpt4 book ai didi

C# - 将实现接口(interface)的对象添加到字典

转载 作者:可可西里 更新时间:2023-11-01 07:53:23 25 4
gpt4 key购买 nike

我有一本字典:

private Dictionary<Type, IExample> examples;

我有两个实现接口(interface)的类:

public class Example1 : IExample
{
}

public class Example2 : IExample
{
}

我已经创建了一种从字典中获取实例(如果它存在)的方法,但我正在尝试找出一种方法来实例化一个新对象(如果它不存在)。

public T GetExample<T>() where T : IExample
{
// Return the signal if it exists
if (examples.ContainsKey(typeof(T)))
{
IExample value;

if (!examples.TryGetValue(typeof(T), out value))
{
// unable to get value
}

return (T)value;
}

// Stuck on this line here. How exactly do I instantiate a new example if it doesn't exist.
examples.Add(typeof(T), new );

return default(T);
}

这样的事情可能吗?

最佳答案

您需要在无参数构造函数的泛型方法上添加泛型类型参数约束,然后您可以实例化类型 T 参数,如 new T() :

public T GetExample<T>() where T : IExample,class,new()
{
IExample value;

if (examples.TryGetValue(typeof(T), out value))
{
return (T)value;
}


T obj = new T(); // create instance of T and use further down in code it's reference
examples.Add(typeof(T),obj );

return obj ;
}

return default(T); 将返回 null 而不是类的 T 的新实例(Reference Types) 默认值为 null,我怀疑你想在那里做 return new T();,这将创建一个新对象并返回对它的引用返回调用者。

关于C# - 将实现接口(interface)的对象添加到字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43513762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com