简体   繁体   English

如何访问不属于接口定义的方法? (同时仍然编程到接口)

[英]How do I access methods that are not part of an interface definition? (while still programming to interfaces)

For a group of classes that all implement the same interface, say one or more have additional methods that are not part of the interface definition. 对于一组都实现相同接口的类,例如,一个或多个具有不属于接口定义的其他方法。 When i create those objects, using the interface is there a way to access those methods? 当我创建这些对象时,使用该接口是否有办法访问这些方法? or do I have to create each individual object without using the interface? 或者我是否必须在不使用界面的情况下创建每个单独的对象?

class Program
{
    static void Main(string[] args)
    {
        ITextProcessor processor = new FileProcessor();
        string result = processor.ReadText();
        processor.SaveText(result);


        ITextProcessor processorTest = new FileProcessorTest();
        processorTest.testMethod() // unavailable

    }
}


class FileProcessor : ITextProcessor
{
    public string ReadText()
    {
        // read in text from a
        // file and return it

        return Console.ReadLine();
    }

    public void SaveText(string processedText)
    {
        // write processedText out to file.
        Console.WriteLine(processedText);
    }
}

class FileProcessorTest : ITextProcessor
{
    public string ReadText()
    {
        // read in text from a
        // file and return it

        return Console.ReadLine();
    }

    public void SaveText(string processedText)
    {
        // write processedText out to file.
        Console.WriteLine(processedText);
    }

    public void testMethod()
    {
       //I want to be able to access this method
    }
}

interface ITextProcessor
{
    string ReadText();
    void SaveText(string processedText);
}

You can't - the whole point of using an interface is that you know that every implementer has every method, which you can't possibly know unless it's declared by the interface. 你不能 - 使用接口的全部意义在于你知道每个实现者都有每个方法,除非接口声明它,否则你不可能知道。

You could get around it by trying to cast to one of the concrete implementations and call the method if successful; 可以通过尝试转换到其中一个具体实现来解决它,如果成功则调用该方法; however, this also defeats the point as interfaces are supposed to abstract these concrete implementations away from the classes using them (and this would not be "still programming to interfaces"). 然而,这也违背了点作为接口从类中使用它们应该是抽象的,这些具体的实现 (这不会是“还是面向接口编程”)。

Consider this: If the class making use of the interface needs to use it for something that is not declared in the interface, is the interface being used the right one? 考虑一下:如果使用接口的类需要将它用于未在接口中声明的内容,那么接口是否正确使用?

One thing you might consider is that perhaps your calling class needs more than just this interface. 您可能会考虑的一件事是,您的调用类可能需要的不仅仅是此接口。 Maybe it needs one of these instead: 也许它需要其中一个:

public interface ITestableTextProcessor : ITextProcessor
{
    void TestMethod();
}

public class FileProcessorTest : ITestableTextProcessor {...}

Of course, whether this is appropriate (or even feasible) depends on what you're doing with it. 当然,这是否合适(甚至可行)取决于你正在做什么。

Yes, it's possible, but not desiderable: 是的,这是可能的,但不是可以想象的:

ITextProcessor processor = new FileProcessorTest();

//what if you have multiple implementations of ITextProcessor with custom methods each?
if (processor is FileProcessorTest) {
    ((FileProcessorTest)processor).testMethod();
}

You could try this: 你可以试试这个:

class Program
{
    static void Main(string[] args)
    {
        ITextProcessor processor = new FileProcessor();
        string result = processor.ReadText();
        processor.SaveText(result);

        ITextProcessor processorTest = new FileProcessorTest();
        if (processorTest is FileProcessorTest)
        {
             ((FileProcessorTest)processor).testMethod();
        }
    }
}

If you don't want to do this check or know in code what instance you have, then maybe it's easier to directly assign the type of the class: 如果你不想这样做检查或在代码中知道你有什么实例,那么可能更容易直接分配类的类型:

FileProcessorTest processorTest = new FileProcessorTest();
processorTest.testMethod();

You can't do this. 你不能这样做。 The interface is there as a "promise" that the classes implementing it will provide all of the declared methods. 接口作为“承诺”,实现它的类将提供所有声明的方法。 If you are going to add members willy-nilly to the derived classes, then that is NOT part of the interface - it's something specific to that specific class. 如果您要将willy-nilly成员添加到派生类中,那么这不是界面的一部分 - 它是特定于该特定类的特定内容。

As such, you must cast the object as that particular class if you want to use the extra method. 因此,如果要使用额外方法,则必须将对象强制转换为特定类。

If you declare it as an interface, then you will only ever get access to methods in the interface - the extra ones will be hidden until you cast. 如果您将其声明为接口,那么您将只能访问界面中的方法 - 额外的方法将被隐藏,直到您进行投射。

In other words: 换一种说法:

class Program
{
    static void Main(string[] args)
    {
        ITextProcessor processor = new FileProcessor();
        string result = processor.ReadText();
        processor.SaveText(result);


        ITextProcessor processorTest = new FileProcessorTest();
        // cast processorTest as the specific type to access the extra method
        ((FileProcessorTest)processorTest).testMethod() 

    }
}

You can't using an Interface in order to invoke another method that's not defined in the interface as this will broke the L of SOLID principles which state that 你不能使用接口来调用另一个未在接口中定义的方法,因为这将破坏SOLID principlesL ,这说明了

objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program

But as stated in other answer you can cast interface variable to the object but this is not recommended especially when you have many types of object inherits from the some interface 但正如在其他答案中所述,您可以将接口变量强制转换为对象但不建议这样做,尤其是当您从某个接口继承了多种类型的对象时

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从实现这两个接口的类访问在两个接口之间定义的参数和方法? - How do I access parameters and methods defined across two interface from a class that implements those two interfaces? 针对接口编程:什么时候不将方法声明为接口方法? - Programming against interfaces: When not to declare methods as interface methods? 如何阅读Google的定义部分? - How do I read the definition part of google? 如何在仍保持动态状态的同时指定接口返回类型? - How do I specify an interface return type while still remaining dynamic? 如何使用接口作为方法参数但仍访问非接口方法? - How to use interface as a method parameter but still access non-interface methods? 如何正确使用 C++ 中的构造函数和方法中的接口? - How do I use interfaces in constructors and methods in C++ properly? 如何重构这两种方法? 第2部分。 - How do I refactor these 2 methods? Part 2. 在没有接口定义的类中添加公共方法是一种好习惯吗? 我什么时候应该这样做? - Is it a good practice to add public methods in a class which are not in Interface definition? When should I do that? 使用显式接口确保针对接口进行编程 - Using explicit interfaces to ensure programming against an interface 如何使用公共属性而不是私有集合方法实现多个接口? - How do I implement multiple interfaces with public properties but private set methods?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM