如何在C#中检查类型是否为字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9517333/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 07:42:49  来源:igfitidea点击:

How to check whether a type is string in C#?

c#

提问by Embedd_Khurja

I want to go through all the properties of a type and want to check whether a property type is not a string, how can I do it ?

我想查看一个类型的所有属性,并想检查一个属性类型是否不是字符串,我该怎么做?

My class is:

我的班级是:

public class MarkerInfo
{
    public string Name { get; set; }
    public byte[] Color { get; set; }
    public TypeId Type { get; set; }
    public bool IsGUIVisible { get; set; }

    public MarkerInfo()
    {
        Color = new byte[4]; // A, R, G, B
        IsGUIVisible = true;
    }
}

the code I am using to check for type is:

我用来检查类型的代码是:

foreach (var property in typeof(MarkerInfo).GetProperties())
{               
    if (property.PropertyType is typeof(string))              
}

But this code is not working, any idea how to do that ?

但是这段代码不起作用,知道怎么做吗?

回答by Darin Dimitrov

if (property.PropertyType == typeof(string))

回答by Ofer

use ==and not isor is String(leave the typeof)

使用==and not isor is String(保留 typeof)

回答by Christian.K

Use the following instead:

请改用以下内容:

foreach (var property in typeof(MarkerInfo).GetProperties())
{               
    if (property.PropertyType == typeof(string))              
}