简体   繁体   中英

How to determine if System.Object is System.Type

I am writing a general IValueConverter for WPF, and i'm coming unstuck on comparing the value to a particular type.

The makeup of my objects in look something like this

public interface IAwesome
{
    int AwesomeAmount { get; set; }
}

public class MyAwesomeClass : IAwesome
{
    public int AwesomeAmount { get; set; }
}

My method looks something like this

public bool CompareToType(object value, Type type);

If I had...

var mac = new MyAwesomeClass();
bool isAwesome = CompareToType(mac, typeof(IAwesome));

Similarly I could write

var stream = new FileStream();
bool isStream = CompareToType(stream, typeof(Stream));

How do I write my CompareToType method to determine if the class implements the Interface or inherits from a base object?

Apologies if i'm missing somethign blindingly obvious, but i'd appreciate some help anyway :)

Use Type.IsAssignableFrom method.

Example:

type.IsAssignableFrom(value.GetType());

maybe you are looking for is ?

var stream = new FileStream();
bool isStream = stream is Stream;

you could also try

isStream = typeOf(Stream).IsAssignableFrom(stream.GetType());

If I understand correctly, your looking for this:

if (mac is IAwesome) {}

Or: var t = mac as IAwesome; if (t != null) {}

bool isAwesome = mac is IAwesome;

To check if a class implements an interface:

var obj = new MyInteracedClass();
typeof(IMyInterface).IsAssignableFrom(obj.GetType());

or

typeof(IMyInterface).IsAssignableFrom(typeof(MyInteracedClass));

The easy implementation is

public bool CompareToType(object obj, Type type)
{
    return type != null
        && obj != null
        && type.IsAssignableFrom(obj.GetType());
}

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