简体   繁体   English

C# - 通用接口

[英]C# - Generic interfaces

Where do generic interfaces are quite useful ? 通用接口在哪里非常有用? ( I am a beginner,so simple example will definitely helpful). (我是初学者,这么简单的例子肯定会有帮助)。

Its useful when you need an interface, but you also need to abstract the data type. 它在您需要接口时很有用,但您还需要抽象数据类型。 Simple example 简单的例子

public interface IMyShape<T>
{
   T X { get; }
   T Y { get; }
}

public class IntSquare : IMyShape<int>
{
   int X { get { return 100; } }
   int Y { get { return 100; } }
}

public class IntTriangle : IMyShape<int>
{
   int X { get { return 200; } }
   int Y { get { return 200; } }
}

public class FloatSquare : IMyShape<float>
{
   float X { get { return 100.05; } }
   float Y { get { return 100.05; } }
}

你可以先看一下IEnumerable<T>

Generic interfaces are really useful when you want to parameterize the types of one of the members in the interface. 当您想要参数化接口中某个成员的类型时,通用接口非常有用。 Consider the IEnumerable and IEnumerable<T> interfaces. 考虑IEnumerableIEnumerable<T>接口。 The first iterates Objects whereas the second iterates instances of the type argument supplied for T . 第一个迭代Objects而第二个迭代为T提供的类型参数的实例。

Since interfaces can be generic it allows you to leverage their flexibility while still taking advantage of generics in the same way that you would for a concrete type. 由于接口可以是通用的,因此它允许您利用其灵活性,同时仍然以与具体类型相同的方式利用泛型。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM