【问题标题】:Understanding Generic method in C#了解 C# 中的泛型方法
【发布时间】:2017-08-10 00:50:23
【问题描述】:

我从 Java 迁移到 C#,我正在用 C# 自动化 web 服务。有一段代码正在调用下面的方法来将 XML 文档转换为字符串

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

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

谁能解释一下上面的方法到底在做什么,我知道返回类型是字符串但是这段代码是什么意思ToXml&lt;T&gt;(this T toSerialize) where T : class

谁能解释一下“通用”是什么意思?

【问题讨论】:

  • 这就是所谓的扩展方法
  • 这是一种扩展方法。首先阅读扩展,然后转到泛型

标签: c# generics


【解决方案1】:

这是一个extension method

public static string ToXml&lt;T&gt;(thisT toSerialize) where T : class

还有一个generic oneconstrained to reference types

public static string ToXml&lt;T&gt;(thisTtoSerialize)where T : class

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

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

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

string xml = foo.ToXml();

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

【讨论】:

    【解决方案2】:
    public static string ToXml<T>(this T toSerialize) where T : class
    

    让我为你分解一下

    <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)
    

    在 C# 中,您可能需要也可能不需要在调用站点显式提供泛型类型信息,具体取决于具体情况。在您的情况下,无需明确说明即可解决

    一个明确指定的调用会喜欢

    var xml = document.ToXml<XmlDocument>();
    

    您已经意识到使用var 关键字而不是显式指定string,因为编译器可以很容易地从上下文中推断出类型。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-30
      • 2011-02-27
      • 2011-04-23
      • 1970-01-01
      相关资源
      最近更新 更多