看很多人都问了接口的问题,但是我现在心中还是有疑问。接口要在支持它的类中实现。我想问的是,如果若干各类都支持这个接口(这些类相互之间没有继承关系),那么是不是每个类中都要写实现接口成员的代码?如果是,那么代码都要一样吗?
还有就是IEnumerable、IColllection、IList这些接口,它们是怎么实现的?也是在类中写代码吗?
还有就是IEnumerable、IColllection、IList这些接口,它们是怎么实现的?也是在类中写代码吗?
public class Person
{
public Person(string fName, string lName)
{
this.firstName = fName;
this.lastName = lName;
} public string firstName;
public string lastName;
} public class People : IEnumerable
{
private Person[] _people;
public People(Person[] pArray)
{
_people = new Person[pArray.Length]; for (int i = 0; i < pArray.Length; i++)
{
_people[i] = pArray[i];
}
} public IEnumerator GetEnumerator()
{
return new PeopleEnum(_people);
}
} public class PeopleEnum : IEnumerator
{
public Person[] _people; // Enumerators are positioned before the first element
// until the first MoveNext() call.
int position = -1; public PeopleEnum(Person[] list)
{
_people = list;
} public bool MoveNext()
{
position++;
return (position < _people.Length);
} public void Reset()
{
position = -1;
} public object Current
{
get
{
try
{
return _people[position];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
}
但每个类实现方法的代码可以不一样!
水平有限,如有不足请大家指证:class Program
{
static void Main(string[] args)
{
ITest test;
test = new DoubleTest(); Console.WriteLine("输出了10加2的数:" + test.Add(10));
Console.WriteLine("输出了10减2的数:" + test.Sub(10)); test = new OneTest();
Console.WriteLine("输出了10加1的数:" + test.Add(10));
Console.WriteLine("输出了10减1的数:" + test.Sub(10));
Console.ReadLine();
}
}
/// <summary>
/// 定义接口
/// </summary>
public interface ITest
{
int Add(int input);
int Sub(int input);
}
/// <summary>
/// 实现加2或者减2的类
/// </summary>
public class DoubleTest : ITest
{ public int Add(int input)
{
return input + 2;
} public int Sub(int input)
{
return input - 2;
}
}
/// <summary>
/// 实现加1或者减1的类
/// </summary>
public class OneTest : ITest
{ public int Add(int input)
{
return input + 1;
} public int Sub(int input)
{
return input - 1;
}
}
可以解释一下吗?有些地方不太懂_person
{
void Show();
}static class IShowHelper
{
public static void Show(this IShow obj) { Console.WriteLine(obj.ToString()); }
}class Foo : IShow()
{
public void Show() { (this As IShow).Show(); }
}
肯定的如果是,那么代码都要一样吗?
根据你的需要写不同的代码
IEnumerable、IColllection、IList这些接口,它们是怎么实现的?也是在类中写代码吗?
和你自定义的接口一样也是用类去实现,
怎么实现,还是根据你自己的需要,看看样例