gpt4 book ai didi

c# - 如何在 C# 中使用泛型声明变量

转载 作者:太空宇宙 更新时间:2023-11-03 18:12:42 26 4
gpt4 key购买 nike

public static object GetObject(int x)
{
return new object { };
}
public static object GetObject(string x)
{
return new object { };
}
public static void ProcessObject<T>(T x) where T : int, string <= got error here:
{
object o = GetObject(x);
}

出现错误“用作约束的类型必须是接口(interface)、非密封类或类型参数。”

如何在不编写 ProcessObject(int x)ProcessObject(string x) 两次的情况下重写代码以使其工作?

最佳答案

那么你现在拥有的(根据接受的答案和你的评论)是:

public static void ProcessObject<T>(T x)
{
object o;
if (typeof(T) == typeof(int))
o = GetObject((int)(object)x);
else if (typeof(T) == typeof(string))
o = GetObject((string)(object)x);
else
throw new Exception();
// do stuff with o
}

我建议公开 intstring 重载,但为了防止代码重复,在内部调用另一个方法:

public static void ProcessObject(int x)
{
ProcessObject(GetObject(x));
}
public static void ProcessObject(string x)
{
ProcessObject(GetObject(x));
}
private static void ProcessObject(object o)
{
// do stuff with o
}

这使您的public 方法的输入值变得清晰:intstring 是唯一可接受的类型,同时仍然不会重复您的实际逻辑(//用 o 做事)。

您可能不喜欢这两个公共(public) ProcessObject 方法彼此重复,(无论如何在表面上;在引擎盖下,它们调用两个不同的 GetObject 重载) 但我认为这是最佳选择。

关于c# - 如何在 C# 中使用泛型声明变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11808466/

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