为什么这个实现方法看不到它的兄弟?

时间:2014-12-01 22:13:36

标签: c# interface interface-implementation

我有一个实现接口的类:

public class SQLiteHHSDBUtils : IHHSDBUtils
{

    void IHHSDBUtils.SetupDB()
    {
            . . .
            if (!TableExists("AppSettings"))

    . . .

    bool IHHSDBUtils.TableExists(string tableName)
    {
    . . .

找不到自己的兄弟坐在它下面(if (!TableExists()):

  

当前上下文中不存在名称“TableExists”

它怎么能/为什么它看不到它?

3 个答案:

答案 0 :(得分:6)

您有一个明确的接口实现。除非将当前实例转换为接口类型,否则无法直接访问接口方法:

if (!((IHHSDBUtils)this).TableExists("AppSettings"))

来自13.4.1 Explicit interface member implementations

  

在方法调用,属性访问或索引器访问中,无法通过其完全限定名称访问显式接口成员实现。显式接口成员实现只能通过接口实例访问,并且在这种情况下仅通过其成员名称引用。

答案 1 :(得分:3)

显式实现接口时,您需要从类型正是接口(而不是实现类型)的变量访问接口成员。

if (!TableExists("AppSettings"))通过TableExists对象调用this,该对象的类型为SQLiteHHSDBUtils,而不是IHHSDBUtils

尝试:

if (!((IHHSDBUtils)this).TableExists("AppSettings"))

或者,不要明确地实现界面:

public class SQLiteHHSDBUtils : IHHSDBUtils
{
    // .. 
    bool TableExists(string tableName)
    {
        // ..

答案 2 :(得分:2)

TableExists是一个明确的实现。如果您想要访问它,则必须将this投射到IHHSDBUtils

void IHHSDBUtils.SetupDB()
{
    . . . 
    if (!((IHHSDBUtils)this).TableExists("AppSettings"))
相关问题