Checking type parameter of a generic method in C#

前端 未结 4 1107
再見小時候
再見小時候 2020-12-02 19:56

Is it possible to do something like this in C#:

public void DoSomething(T t)  
{
    if (T is MyClass)
    {
        MyClass mc = (MyClass)t 
               


        
4条回答
  •  甜味超标
    2020-12-02 20:26

    Starting with C# 7, you can do this in a concise way with the is operator:

    public void DoSomething(T value)  
    {
        if (value is MyClass mc)
        {
            ...
        }
        else if (value is List lmc)
        {
            ...
        }
    }
    

    See documentation: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/is#pattern-matching-with-is

提交回复
热议问题