简体   繁体   中英

C#: how do I determine type of an interface variable?

I have a interface variable IAction nextAction.

I want to see if the nextAction is of a concrete implementation, but was unsuccessful when I tried the following:

IAction nextAction = GetNextAction();

if (nextAction.GetType() != typeof(LastAction)) {
 // do something...
}

any ideas on how I can determine the concrete type of the IAction variable nextAction?

I believe "is" is what you're looking for. In general:

if (nextAction is ButtonClickedAction) {
   ...
}

On second inspection, it looks like you're trying to see if the action has changed

private void DetermineIfActionChanged(IAction lastAction)
{
   IAction nextAction = GetNextAction();
   if (nextAction.GetType() != lastAction.GetType())
   {
       DoSomethingAwesome();
   }
}

The only problem with this approach is if you have some kind of inheritance that you want to respect and you're not concerned about an exact match (eg EventArg versus ClickEventArg would both be considered the same type since ClickEventArg derives from EventArg). If that is the case this SO answer might be of some help .

You can use either use typeof() function or you can use the is operator.

typeof :

IAction nextAction = GetNextAction();

if (nextAction.GetType() != typeof(LastAction)) {
 // do something...
}

Keep in mind that typeof will only return true if the type is exactly the same.

is :

IAction nextAction = GetNextAction();

if (nextAction is LastAction) {
 // do something...
}

But you should keep in mind that the is operator can be used for interfaces and it also respects the inheritance. Read this: What is the difference between typeof and the is keyword?

nextAction.GetType() will give you the concrete type of the object.

However, this is not very good design, the point of an interface is that you use only the shared functionality available in the interface.

If you need functionality that is not covered by the interface then you should declare the variable of the type you need and be done with it.

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