Dynamic casting

Why the last two lines do not work and give me

Could not find type name or namespace 'myType'

Type myType = this.GetType();

bool test = obj is myType;
var p = (myType)obj;
+3
source share
6 answers

You need to do:

bool test = myType.IsInstanceOfType(obj);

or

bool test = myType.IsAssignableFrom(obj.GetType());
// var p = Convert.ChangeType(obj, myType); - update: this is not what the OP asked

For the second, you cannot "distinguish" an expression from a type that is unknown at compile time. The casting point must refer to members of this type initially. If you do not know that the type is in the compilation type (because you are using .GetType()), then there is no caste, and perhaps this is not possible.

+4
source

# - , , . var ", ( ) ".

. Type, . .NET Reflection.

, , . , - :

bool test = myType.IsInstanceOfType(obj);
bool test = typeof(obj).IsAssignableFrom(myType); // Good for checking if a type implements an interface

object :

object p = obj;
+3

, , #. , . , .

, p? , .

+1

, Type , :

Type thisType = this.GetType();
Type objType = obj.GetType();

if(objType.IsAssignableFrom(type))
{
     // do your stuff
}

, . , # 4, dynamic.

Type thisType = this.GetType();
Type objType = obj.GetType();

if(objType.IsAssignableFrom(type))
{
    dynamic dynObj = obj;
    dynObj.CallWhateverIWant();
}

, , , , , . , - , , .

+1

I don't have finished Visual Studio at the moment, and this is not something I need to do often, but for the second line, I think it should look like this:

bool test = obj is typeof(this);

The third line is not possible if you do not have a limited set of possible types that you can include.

0
source

the is operator works on classes, not on objects of type Type

If you want to do this, use the dynamic keyword

http://msdn.microsoft.com/en-us/library/dd264736.aspx

0
source

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


All Articles