gpt4 book ai didi

C# 泛型和类型检查

转载 作者:IT王子 更新时间:2023-10-29 03:43:43 24 4
gpt4 key购买 nike

我有一个使用 IList<T> 的方法作为参数。我需要检查那个 T 的类型对象是并基于它做一些事情。我正在尝试使用 T值,但编译器不允许。我的解决方案如下:

private static string BuildClause<T>(IList<T> clause)
{
if (clause.Count > 0)
{
if (clause[0] is int || clause[0] is decimal)
{
//do something
}
else if (clause[0] is String)
{
//do something else
}
else if (...) //etc for all the types
else
{
throw new ApplicationException("Invalid type");
}
}
}

必须有更好的方法来做到这一点。有什么方法可以检查 T 的类型吗?传入然后使用 switch声明?

最佳答案

你可以使用重载:

public static string BuildClause(List<string> l){...}

public static string BuildClause(List<int> l){...}

public static string BuildClause<T>(List<T> l){...}

或者您可以检查泛型参数的类型:

Type listType = typeof(T);
if(listType == typeof(int)){...}

关于C# 泛型和类型检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/982952/

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