WITH#. Determine at run time if the property is an instance of a type or object?

I want to determine if it is assigned to MyBindingSource.DataSourcea set of constructors Type, or if an object instance has been assigned to it. This is my current (rather ugly) solution:

Type sourceT = MyBindingSource.DataSource.GetType();
if( sourceT == null || sourceT.ToString().Equals("System.RuntimeType") ) {
     return null;
}
return (ExpectedObjType) result;

System.RuntimeType is closed and inaccessible, so I can not do this:

Type sourceT = MyBindingSource.DataSource.GetType();
if ( object.ReferenceEquals(sourceT, typeof(System.RuntimeType)) ) {
     return null;
}
return (ExpectedObjType) result;

I'm just wondering if there is a better solution? In particular, this does not apply to the name Type.

+3
source share
2 answers

Since System.RuntimeTypeobtained from System.Type, you should be able to do the following:

object result = MyBindingSource.DataSource;
if (typeof(Type).IsAssignableFrom(result.GetType()))
{
    return null;
}
return (ExpectedObjType)result;

or even more briefly:

object result = MyBindingSource.DataSource;
if (result is Type)
{
    return null;
}
return (ExpectedObjType)result;

By the way, this is the approach taken here .

+1

ToString(); GetType() ( ). , , , " ", , , , RuntimeType. " " , .

, , RuntimeType, , . , Type, RuntimeType, " ".

+1

Source: https://habr.com/ru/post/1767575/


All Articles