简体   繁体   中英

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

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 ?

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

Use the following instead:

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

使用==而不是is or is String (保留 typeof)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM