理解C#中的泛型方法

时间:2017-08-09 16:17:13

标签: c# generics

我从Java迁移到C#,我在C#中自动化Web服务。有一段代码调用下面的方法将XML文档转换为String

XmlDocument document = new XmlDocument();
document.Load(filePath + fileName);            
var xml = document.ToXml();

public static string ToXml<T>(this T toSerialize) where T : class

有人可以解释一下上面的方法究竟是做什么的,我理解返回类型是String但是这段代码是什么意思ToXml<T>(this T toSerialize) where T : class

有人也能解释一下“通用”是什么意思吗?

2 个答案:

答案 0 :(得分:3)

它是extension method

public static string ToXml<T>( this T toSerialize) where T : class

generic one就是constrained to reference types

public static string ToXml <T> (this T toSerialize) where T : class

这意味着您可以在任何引用类型上调用该方法:

var foo = new YourClass
{
    Bar = "Baz"
};
string xml = foo.ToXml<YourClass>();

因为泛型参数类型用作引用类型,所以可以让它为inferred,省略泛型参数:

string xml = foo.ToXml();

您也可以使用File.ReadAllText()将文本文件加载到字符串中。

答案 1 :(得分:1)

func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
    let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
    pageControl.currentPage = Int(pageNumber)
}

让我为你分解

public static string ToXml<T>(this T toSerialize) where T : class

在C#中,您可能需要或不必在呼叫站点明确提供通用类型信息,具体取决于具体情况。在您的情况下,它将被解决而无需显式规范

显式指定的调用类似于

<T>                  // This is the templated or generic type name.
where T : class      // This syntax restricts the generic type to be a class (as opposed to a struct)
this T toSerialize)  // The "this" keyword here can be ignored as it has nothing to do with the generics. It just tells that the caller can call this method like toSerialize.ToXml() instead of ContainingClass.ToXml(toSerialize)

正如您已经意识到使用var xml = document.ToXml<XmlDocument>(); 关键字而不是显式指定var,因为编译器可以很容易地从上下文中推断出类型。

您可以阅读Genericscontraints。此外,您可以阅读Extension Methods。这应该让你对所涉及的句法元素有充分的理解