开发者

How can we implement the two interfaces having same method names?

开发者 https://www.devze.com 2023-01-22 13:44 出处:网络
I have a question that how can we implement the interfaces having same methodnames like this interface ISample2

I have a question that how can we implement the interfaces having same methodnames like this

 interface ISample2
{
  string CurrentTime();
     string CurrentTime(string name);
}
 interface ISample1
{
     string CurrentTime();
}

I did like this .Is this right?

class TwoInterfacesHavingSameMethodName:ISample1,ISample2
{
    static void Main(string[] sai)
    {
        ISample1 obj1 = new TwoInterfacesHavingSameMethodName();
        Console.Write(obj1.CurrentTime());
        ISample2 obj2 = new TwoInterfacesHavingSameMethodName();
        Console.Write(obj2.CurrentTime("SAI"));
        Console.ReadKey();
    }

    #region ISample1 Members

    string ISample1.CurrentTime()
    {
        return "Interface1:" + DateTime.Now.ToString();
    }

    #endregion

    #region ISample2 Members

    string ISample2.CurrentTime()
    {
        return "Interface2:FirstMethod" + DateTime.Now.ToString();
    }

    string ISample2.CurrentTime(string name)
    {
        return "Interface2:SecondMethod" + DateTime.Now.ToString() + "" + name;
    }

    #endregion
}

开发者_Python百科Here what is the meaning of this line:

ISample1 obj1 = new TwoInterfacesHavingSameMethodName();

Are we creating object for Class or Interface.What is the basic use of writing the methods in Interface.


When you explicitly implement an interface the explicit implementation will be called only if you call it from a reference to that interface.

so if you will write:

  TwoInterfacesHavingSameMethodName obj1 = new TwoInterfacesHavingSameMethodName();
  obj1.CurrentTime();

you will get an error.

but

ISample1 obj1 = new TwoInterfacesHavingSameMethodName();
ISample2 obj2 = new TwoInterfacesHavingSameMethodName();
obj1.CurrentTime();
obj2.CurrentTime();

will work.

if you want to call this function also on TwoInterfacesHavingSameMethodName you have to implicitly implement the interface as well. for ex:

public string CurrentTime()
{
   return "Implicit";
}


Yes, what you did is correct. To answer your second question, you always create an object of a class and of type the interface. The use of writing methods in interface is to enforce all the classes to implement that method.

0

精彩评论

暂无评论...
验证码 换一张
取 消