我有 2 个接口,
public interface I1
{
string GetRandomString();
}
public interface I2
{
string GetRandomString();
}
Run Code Online (Sandbox Code Playgroud)
在课堂上,我植入了两者,
public class ClassA : I1, I2
{
string I1.GetRandomString()
{
return "GetReport I1";
}
string I2.GetRandomString()
{
return "GetReport I1";
}
}
Run Code Online (Sandbox Code Playgroud)
现在在主方法中我想访问这些接口方法但无法访问
static void Main(string[] args)
{
var objClassA = new ClassA();
objClassA.GetRandomString(); // not able to do this, comile time error ...
}
Run Code Online (Sandbox Code Playgroud)
我知道,我缺少一些基本的 OOPS 东西,只是想知道这一点。有什么帮助吗?
如果您有时想使用一个接口,有时想使用另一个接口,则可能有必要对其中最后一个接口使用强制转换。如果您控制类型并且可以直接使用其中一个接口函数而不是作为显式实现,那么将避免对该接口函数进行强制转换的要求。为了避免必须对任一函数进行类型转换,您应该在对象中以单独的名称提供它们。因为在 C# 中,任何实现 anyInterface.Boz 的方法都必须调用 Boz,所以最好的方法可能是让 IFoo.Boz 和 IBar.Boz 的实现简单地调用名为 FooBoz 和 BarBoz 的公共方法,然后可以“直接”调用这些方法,而无需歧义。
虽然对于类来说,转换到接口的成本很低,但对于结构来说,转换到接口的成本可能很高。在某些情况下,可以通过使用如下所示的静态方法来避免这种成本:
公共接口 AliceFoo { void foo();};
公共接口 BobFoo { void foo();};
static void do_alice_foo<T>(ref T it) 其中 T:AliceFoo
{
it.foo();
}
static void do_bob_foo<T>(ref T it) 其中 T : BobFoo
{
it.foo();
}
这种方法允许使用“foo”方法,而无需进行任何类型转换。