Passing a dynamic variable to the specified type

I have a dynamic variable in which I store an object, which can be of several types, depending on the context (here Foo and Bar)

dynamic myvar;
myvar = new Foo();
//or
myvar = new Bar();

Foo and Bar contain various methods. To access myvar methods, I thought you could use roles like

(Foo)myvar.mymethodoffoo();
(Bar)myvar.mymethodofbar();

But it does not work, I get (dynamic expression), this operation will be allowed at runtime in the code editor.

So, how can I create a dynamic object to get the available methods and properties from the editor?

Thanks in advance.

+3
source share
2 answers

((SomeType)x) , ..
(Bar)(myvar.mymethodofbar()) — .

:

((Bar)myvar).mymethodofbar();
+10
((Foo)myvar).mymethodoffoo();
((Bar)myvar).mymethodofbar();
+2

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


All Articles