在C#/ VB.NET中使用泛型的哪些示例以及为什么要使用泛型?
答案 0 :(得分:61)
简单地说,您声明一个带有额外标签的类型或方法来指示通用位:
class Foo<T> {
public Foo(T value) {
Value = value;
}
public T Value {get;private set;}
}
上面定义了Foo
“的泛型T
”,其中T
由调用者提供。按照惯例,泛型类型参数以T开头。如果只有一个,T
就可以了 - 否则将它们全部命名为:TSource
,TValue
,TListType
等
与C ++模板不同,.NET泛型由运行时提供(不是编译器技巧)。例如:
Foo<int> foo = new Foo<int>(27);
以上所有T
已被int
替换。如有必要,可以使用约束限制泛型参数:
class Foo<T> where T : struct {}
现在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
约束也可以涉及其他泛型类型参数,例如:
T : IComparable<T> // or another type argument
您可以根据需要拥有任意数量的通用参数:
public struct KeyValuePair<TKey,TValue> {...}
其他注意事项:
Foo<int>
上的静态字段与Foo<float>
上的静态字段分开。例如:
class Foo<T> {
class Bar<TInner> {} // is effectively Bar<T,TInner>, for the outer T
}
答案 1 :(得分:7)
示例1:您想要创建三级
Class Triple<T1, T2, T3>
{
T1 _first;
T2 _second;
T3 _Third;
}
示例2:将解析给定数据类型
的任何枚举值的辅助类static public class EnumHelper<T>
{
static public T Parse(string value)
{
return (T)Enum.Parse(typeof(T), value);
}
}
答案 2 :(得分:4)
泛型的一个常见且非常有用的用途是强类型集合类。传统上,所有集合类都必须传递对象,并在查询时返回对象。您必须自己处理所有类型转换。使用泛型,您不必这样做。您可以拥有List(Of Integer),当您从中请求值时,您将获得整数。您将无法获得必须转换为整数的对象。
答案 3 :(得分:3)
以前提到的MSDN文档中描述了泛型的最常见原因和用例。我想添加的泛型的一个好处是它们可以增强开发过程中的工具支持。像Visual Studio或ReSharper中集成的重构工具依赖于静态类型分析来在编码时提供帮助。由于泛型通常会向对象模型添加更多类型信息,因此有更多信息可供此类工具进行分析并帮助您进行编码。
在概念层面上,泛型可帮助您独立于应用程序域解决“交叉”问题。无论您是在开发金融应用程序还是书店,您迟早都需要维护一些东西,无论是帐户,书籍还是其他什么东西。这些集合的实现通常需要对这些集合中要维护的事物几乎一无所知。因此,.NET框架附带的通用集合是泛型用例的主要示例。
答案 4 :(得分:3)
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; }
}
答案 5 :(得分:1)
一个基本的例子是:
class Other{
class Generic<T>
{
void met1(T x);
}
static void Main()
{
Generic<int> g = new Generic<int>();
Generic<string> s = new Generic<string>();
}
}
答案 6 :(得分:0)
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; }
}