How can I use an interface as my type in C #?

I have a property that returns an interface. During debugging, I can break what was returned, and although it is an interface, Visual Studio is smart enough to know the derived type that it actually is. I guess it uses reflection or something else. I'm not sure. My question is: can I have the same information available to me at runtime so that I can create a variable of the appropriate type and strip the interface? Here is what I am saying:

IPreDisplay preDisplay = cb.PreDisplay;

If preDisplay is RedPreDisplay, I would like to be able to code

RedPreDisplay tmp = preDisplay as RedPreDisplay;

Or, if preDisplay was GreenPreDisplay ...

GreenPreDisplay tmp = preDisplay as GreenPreDisplay;

etc ... I would like to avoid the messy switch statement if possible, and if I could use generics, which would be great.

- , , .

+3
5

, , , - . , , . , , - , .

, - - if/else , . , , -, , - , . .

: , , . :

IPreDisplay display = cb.PreDisplay;
IOtherInterface displayAsOther = display as IOtherInterface;
if(displayAsOther != null)
{
    displayAsOther.OtherMethod();
}
+17

, . , , , .

, ( ). , .

+6

, , , , / action, - .

:

 IResultLiteEntity preDisplay = cb.PreDisplay;
 preDisplay.Render (); // New Render method on the interface...
+4

@Rex M . . , , ; .

, is, , . :

if(myInstance is MyBaseType)
{
  MyBaseType myInstanceAsBaseType = myInstance as MyBaseType;
  // handle MyBaseType specific issue
}
else if(myInstance is MyOtherBaseType)
{
  MyOtherBaseType myInstanceAsOtherBaseType = myInstance as MyOtherBaseType;
  // handle MyOtherBaseType specific issue.
}

Generics , switch. - , .

+3

, , , , , .

, , :

  • .. , , , (.. ..).
  • if/else if/else . # 4.0.
  • If you use C # 4.0, you can use the object assignment for the dynamic var , and at run time you can use the overloaded method whose signature changes for each supported type (see example below).

Here is an example of C # 4.0 dynamic dispatch:

void Foo()
{
  dynamic preDisplay = cb.PreDisplay;
  DoSomethingWith( preDisplay );  // runtime dispatch using dynamic runtime (DLR)
}

void DoSomethingWith( RedPreDisplay r ) { ... }  // code specific to RefPreDisplay
void DoSomethingWith( GreenPreDisplay g ) { ... } // code specific to GreenPreDisplay
void DoSomethingWIth( IPreDisplay o ) { ... }  // catch-all
+3
source

All Articles