问题
Is it possible to cast from one interface to another when both interface's signatures are same? The below source is giving the Unable to cast object of type 'ConsoleApplication1.First' to type 'ConsoleApplication1.ISecond'.
exception.
class Program
{
static void Main(string[] args)
{
IFirst x = new First();
ISecond y = (ISecond)x;
y.DoSomething();
}
}
public interface IFirst
{
string DoSomething();
}
public class First : IFirst
{
public string DoSomething()
{
return "done";
}
}
public interface ISecond
{
string DoSomething();
}
回答1:
Is it possible to cast from one interface to another when both interface's signatures are same?
No. They're completely different types as far as the CLR and C# are concerned.
You could create a "bridge" type which wraps an implementation of IFirst
and implements ISecond
by delegation, or vice versa.
回答2:
As Jon Skeet already answered, no, you can't.
if your problem is to write truely generic code, and if you don't control the interfaces (as in the solution proposed by Baboon), you can still do this two ways in C#:
1 - Reflection
...using reflection to query for the method you want to call:
object x = new First();
Type t = x.GetType();
MethodInfo mi = t.GetMethod("DoSomething");
mi.Invoke(x, new object[]{}); // will call x.DoSomething
2 - dynamic (C# 4)
in C# 4, using the dynamic
keyword to resolve the call at runtime instead of compile time:
object x = new First();
dynamic d = x ; // every call through d will be resolved at runtime
d.DoSomething() ; // compiles (but will throw if there is no
// "DoSomething" method
回答3:
One way i can think of is this:
public interface IDoSomething
{
string DoSomething();
}
public interface IFirst : IDoSomething {}
public interface ISecond : IDoSomething {}
Then instead of casting to IFirst or ISecond, cast to IDoSomething.
来源:https://stackoverflow.com/questions/9428247/cast-between-interfaces-whose-interface-signatures-are-same