首页 > 解决方案 > 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;
    }
}

但是一些通用的语法问题。

问题:这个的正确语法是什么?

标签: c#generics

解决方案


将您的方法重新声明为通用方法会很好:

public static T GetNumber<T>(myList<T> myList) where T : struct

这样做可以避免任何强制转换,并且方法的主体将变为单行,如下所示:

return myList?.numb ?? 0;

推荐阅读