是否可以在C#接口内部使用类型为接口的数据成员? [英] Is it possible to have a data member inside a C# interface with the type as of interface ?

查看:223
本文介绍了是否可以在C#接口内部使用类型为接口的数据成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#中的接口是否有一个具有接口类型的数据成员,这可以用于类?



例如:

Class SomeClass {

//定义了一些属性

//方法如下:
void method1(SomeClass var1,int var2){

//要执行的一组陈述

}}



这里有问题,我指的是在类的方法中传递的参数类型与类本身的类型相同。



Q.那么,这也可以通过接口实现吗? />


我尝试了什么:



研究可以有一个的课程,它也适用于界面吗?

Can an Interface in C# have a data member with the type of interface itself, which is possible with classes?

For example:
Class SomeClass {
//Some properties defined
//Method follows as
void method1 (SomeClass var1, int var2) {
//set of statements to be executed
}}

Here in question, I am referring to the type of parameter passed in the method of class which is of same type as of class itself.

Q. So, is this possible with an Interface as well?

What I have tried:

Research over classes that can have one, does it apply to the interface as well?

推荐答案

没有。接口根本不能包含任何具体方法,只能包含必须通过继承类实现的抽象定义。



抽象类可以定义具体方法,但接口不能。
No. An Interface cannot contain any concrete methods at all, only abstract definitions which must be implemented by inheriting classes.

Abstract classes can define concrete methods, but Interfaces cannot.


是的这也适用于接口。


Quote:

例如:

Class SomeClass {

//定义了一些属性

//方法如下

void method1 (SomeClass var1,int var2){

//要执行的语句集

}}



这里有问题,我指的是类方法中传递的参数类型,它与类本身的类型相同。

For example:
Class SomeClass {
//Some properties defined
//Method follows as
void method1 (SomeClass var1, int var2) {
//set of statements to be executed
}}

Here in question, I am referring to the type of parameter passed in the method of class which is of same type as of class itself.



这是可能的(虽然不是你问的问题标题),例如


This is possible (albeit is not what you asked in question title), for instance

interface IMyInterface
{
  void report(IMyInterface mi);
  int id
  {
    get;
  }
}

class MyClass : IMyInterface
{
  int _id;
  public MyClass(int i) { _id = i; }
  public void report(IMyInterface mi)
  {
    Console.WriteLine("{0}", mi.id);
  }
  public int id
  {
    get { return _id; }
  }
}

class Program
{
  static void Main()
  {
    MyClass a = new MyClass(5);
    MyClass b = new MyClass(-1);
    b.report(a);
  }
}


这篇关于是否可以在C#接口内部使用类型为接口的数据成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆