Best way to test if a generic type is a string? (C#)

后端 未结 6 1164
不知归路
不知归路 2020-12-13 01:09

I have a generic class that should allow any type, primitive or otherwise. The only problem with this is using default(T). When you call default on a value type

6条回答
  •  不知归路
    2020-12-13 01:43

    I know this question is old, but there has been an update.

    Since C# 7.0 you can use the is operator to compare types. You no longer require the usage of typeof as in the accepted answer.

            public bool IsObjectString(object obj)
            {
                return obj is string;
            }
    

    https://docs.microsoft.com/en-US/dotnet/csharp/language-reference/keywords/is

提交回复
热议问题