问题描述
大家好,我有一个问题,我们如何实现具有相同方法名的接口,如下所示:
Hi everyone, 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:
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
}
这条线的含义是什么:
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?
推荐答案
TwoInterfacesHavingSameMethodName obj = new TwoInterfacesHavingSameMethodName();
ISample1 sample1 = (ISample1)obj;
ISample2 sample2 = (ISample2)obj;
ISample1 obj1 = new TwoInterfacesHavingSameMethodName();
接口就像合同.通过实现一个接口,您可以使您的类遵守该接口中定义的约定.使用该对象实例的任何内容都不需要知道有关实例本身的任何信息,只需知道它实现的接口即可.定义的合同.
An interface is like a contract. By implementing an interface you''re making your class abide by the contract defined in the interface. Anything using that object instance doesn''t need to know anything about the instance itself, just the interface it implements, ie. the defined contract.
interface IOne
{
void Foo();
}
interface ITwo
{
void Foo();
}
class Program : IOne, ITwo
{
static void Main(string[] args)
{
IOne one = new Program();
ITwo two = new Program();
one.Foo();
two.Foo();
}
public void Foo()
{
Console.WriteLine("Foo");
}
}
这篇关于如何实现具有相同方法名称的两个接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!