.Net (C#/VB.NET) 中泛型的使用示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/692540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 13:42:35  来源:igfitidea点击:

Examples of usage of Generics in .Net (C#/VB.NET)

c#.netvb.netgenerics

提问by Seenu

What are some examples of where you would use generics in C#/VB.NET and why would you want to use generics?

在 C#/VB.NET 中使用泛型的地方有哪些示例,为什么要使用泛型?

回答by Marc Gravell

Simply, you declare a type or method with extra tags to indicate the generic bits:

简单地说,你声明一个带有额外标签的类型或方法来指示通用位:

class Foo<T> {
    public Foo(T value) {
        Value = value;
    }
    public T Value {get;private set;}
}

The above defines a generic type Foo"of T", where the Tis provided by the caller. By convention, generic type arguments start with T. If there is only one, Tis fine - otherwise name them all usefully: TSource, TValue, TListTypeetc

上面定义了一个泛型类型Foo“of T”,其中T由调用者提供。按照惯例,一般类型参数启动与T.如果只有一个,T是好的-否则他们的名字都有效:TSourceTValueTListType

Unlike C++ templates, .NET generics are provided by the runtime (not compiler tricks). For example:

与 C++ 模板不同,.NET 泛型由运行时提供(不是编译器技巧)。例如:

Foo<int> foo = new Foo<int>(27);

All Ts have been replaced with intin the above. If necessary, you can restrict generic arguments with constraints:

上面的所有Ts都被替换了int。如有必要,您可以使用约束来限制泛型参数:

class Foo<T> where T : struct {}

Now Foo<string>will refuse to compile - as stringis not a struct (value-type). Valid constraints are:

现在Foo<string>将拒绝编译 - 因为string不是结构(值类型)。有效的约束是:

T : class // reference-type (class/interface/delegate)
T : struct // value-type except Nullable<T>
T : new() // has a public parameterless constructor
T : SomeClass // is SomeClass or inherited from SomeClass
T : ISomeInterface // implements ISomeInterface

Constraints can also involve other generic type arguments, for example:

约束还可以涉及其他泛型类型参数,例如:

T : IComparable<T> // or another type argument

You can have as many generic arguments as you need:

您可以根据需要拥有任意数量的通用参数:

public struct KeyValuePair<TKey,TValue> {...}

Other things to note:

其他注意事项:

  • static members etc are defined per generic type combination- so a static field on Foo<int>is separate to that on Foo<float>.
  • methods can be generic too - try to avoid using the same names as the class uses, as you won't be able to disambiguate
  • nested types inherit the generic types from their parents
  • 静态成员等是按泛型类型组合定义的- 因此静态字段 onFoo<int>与on分开Foo<float>
  • 方法也可以是通用的 - 尽量避免使用与类使用的名称相同的名称,因为您将无法消除歧义
  • 嵌套类型从其父级继承泛型类型

for example:

例如:

class Foo<T> {
    class Bar<TInner> {} // is effectively Bar<T,TInner>, for the outer T
}

回答by Brijesh Mishra

Example 1: You want to create triple class

示例 1:您要创建三重类

Class Triple<T1, T2, T3>
{
   T1 _first;
   T2 _second;
   T3 _Third;
}

Example 2: A helper class that will parse any enum value for given data type

示例 2:将解析给定数据类型的任何枚举值的帮助器类

static public class EnumHelper<T>
{
   static public T Parse(string value)
   {
       return (T)Enum.Parse(typeof(T), value);
   }
}

回答by Sven Künzler

The most common reasons and use cases for generics are described in the MSDN documentation mentioned before. One benefit of generics I'd like to add is that they can enhance the tool support in the development process. Refactoring tools like those integrated in Visual Studio or ReSharper rely on static type analysis for providing assistance while coding. As generics usually add more type information to your object model, there is more information for such tools to analyse and to help you coding.

泛型最常见的原因和用例在前面提到的 MSDN 文档中有所描述。我想补充的泛型的一个好处是它们可以增强开发过程中的工具支持。像集成在 Visual Studio 或 ReSharper 中的那些重构工具依赖静态类型分析在编码时提供帮助。由于泛型通常会向您的对象模型添加更多类型信息,因此此类工具有更多信息可供分析和帮助您编码。

On a conceptual level, generics help you solving "cross-cutting" concerns independently from your application domain. Regardless whether you are developing a financial application or a book store, you will sooner or later need to maintain collections of things, be it accounts, books or whatever. The implementation of such collections usually needs to know little to nothing about the things to be maintained in those collections. Hence, the generic collections shipped with the .NET framework are a primary example for a generics use case.

在概念层面上,泛型可帮助您独立于应用程序域解决“横切”问题。无论您是在开发财务应用程序还是书店,您迟早都需要维护收藏品,无论是帐户、书籍还是其他任何东西。这些集合的实现通常需要对这些集合中要维护的东西知之甚少或一无所知。因此,.NET 框架附带的泛型集合是泛型用例的主要示例。

回答by Instance Hunter

One common, and extremely helpful, use of generics is strongly-typed collection classes. Traditionally, all collection classes had to be passed objects, and return objects when queried. You had to handle all the type conversion yourself. With generics, you don't have to do that. You can have List(Of Integer), and when you request values from it, you'll get integers. You won't get objects that you then have to convert to integers.

泛型的一种常见且非常有用的用法是强类型集合类。传统上,所有集合类都必须传递对象,并在查询时返回对象。您必须自己处理所有类型转换。使用泛型,您不必这样做。您可以拥有 List(Of Integer),当您从中请求值时,您将获得整数。您不会得到随后必须转换为整数的对象。

回答by dewelloper

    private void button1_Click_1(object sender, RoutedEventArgs e)
    {
        TextValue<string, int> foo = new TextValue<string, int>("",0);
        foo.Text = "Hi there";
        foo.Value = 3995;
        MessageBox.Show(foo.Text);
    }

    class TextValue<TText, TValue>
    {
        public TextValue(TText text, TValue value)
        {
            Text = text;
            Value = value;
        }
        public TText Text { get; set; }
        public TValue Value { get; set; }
    }

回答by dewelloper

    private void button1_Click_1(object sender, RoutedEventArgs e)
    {
        TextValue<string, int> foo;
        List<TextValue<string, int>> listTextValue = new List<TextValue<string, int>>();
        for (int k = 0; k < 5; ++k)
        {
            foo = new TextValue<string, int>("",0);
            foo.Text = k.ToString();
            foo.Value = k;
            listTextValue.Add(foo);
            otherList.
            MessageBox.Show(foo.Text);
        }

    }

    class TextValue<TText, TValue>
    {
        public TextValue(TText text, TValue value){Text = text; Value = value;}
        public TText Text { get; set; }
        public TValue Value { get; set; }
    }

回答by user544079

A basic example would be:

一个基本的例子是:

class Other{
 class Generic<T>
{
  void met1(T x);
}
static void Main()
{
  Generic<int> g = new Generic<int>();
  Generic<string> s = new Generic<string>();
}
}