c# - C# 泛型类型比较
问题描述
我有这个代码:
public class myList<T> where T : struct
{
public int number { get; set; }
}
public class TypeTest
{
public static int GetNumber(object x)
{
// if (x.GetType() == typeof(myList<>)) // this works BUT I want to use is
if (x is myList<>) // how is the correct syntax for this?
{
int result = ((myList<>)x).numb; //does not compile
return result;
}
return 0;
}
}
但是一些通用的语法问题。
问题:这个的正确语法是什么?
解决方案
将您的方法重新声明为通用方法会很好:
public static T GetNumber<T>(myList<T> myList) where T : struct
这样做可以避免任何强制转换,并且方法的主体将变为单行,如下所示:
return myList?.numb ?? 0;
推荐阅读
- python - 在python中插入/调整ascii艺术?
- cmd - "C:\Users\" 它不被识别为内部或外部命令、可执行程序或批处理文件
- r - 提取两个不同分辨率和范围的栅格中的土地覆盖数据
- swift - 我们可以避免像在 Kotlin 中那样进一步减少 Swift 的冗长吗?
- python - 如何使用 python 和 openCV 从 .yuv 视频文件 (YUV420) 中提取帧?
- node.js - 如何找出错误 500 , Node/ReactJs 的位置
- python - Python 中的 Miller-Rabin Primality Test:为什么我不断得到小数。溢出:[
]? - react-native - 如何在本机反应中将文本转换为语音?
- java - 如何使用 Java 中的文本文件计算数组中整数元素的总和?
- android - 带有 SnapHelper 装饰的 RecyclerView