Why does this implementer method not see its sibling? [closed]

試著忘記壹切 提交于 2019-12-03 01:13:56

问题


I've got a class that implements an interface:

public class SQLiteHHSDBUtils : IHHSDBUtils
{

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

    . . .

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

It can't find its own brother sitting right below it (the if (!TableExists()):

The name 'TableExists' does not exist in the current context

How can it / why does it not see it?


回答1:


You have an explicit interface implementation. You can't access your interface methods directly unless you cast current instance to interface type:

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

From 13.4.1 Explicit interface member implementations

It is not possible to access an explicit interface member implementation through its fully qualified name in a method invocation, property access, or indexer access. An explicit interface member implementation can only be accessed through an interface instance, and is in that case referenced simply by its member name.




回答2:


When you explicitly implement an interface, you need to access the interface member from a variable whose type is exactly the interface (not an implementing type).

if (!TableExists("AppSettings")) is calling TableExists via the this object, whose type is SQLiteHHSDBUtils, not IHHSDBUtils.

Try:

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

Alternatively, don't explicitly implement the interface:

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



回答3:


TableExists is an explicit implementation. If you want to access it, you have to cast this to IHHSDBUtils:

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


来源:https://stackoverflow.com/questions/27238333/why-does-this-implementer-method-not-see-its-sibling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!