传递一个“变种”到另一种方法 [英] Passing a 'var' into another method

查看:118
本文介绍了传递一个“变种”到另一种方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能完全错过了点,但在这里......

I am probably totally missing the point here but....

我如何传递一个变种到另一个方法是什么?

How can I pass a 'var' into another method?

(我使用LINQ to XML加载到对象的可枚举列表)。

(I am using linq to load XML into an Enumerable list of objects).

我有differernt对象类型(具有不同的场),但无论我的方法的最终步骤是相同的​​被使用,其中对象

I have differernt object types (with different fields), but the final step of my process is the same regardless of which object is being used.

XNamespace xmlns = ScehmaName;
var result = from e in XElement.Load(XMLDocumentLocation).Elements(xmlns + ElementName)
             select new Object1
             {
                 Field1 = (string)e.Element(xmlns + "field1"),
                 Field2 = (string)e.Element(xmlns + "field2")
             };

var result2 = Enumerable.Distinct(result);

这code将为不同类型的XML文件将被处理有所不同。但我想,然后遍历虽然code,检查各种问题:

This code will vary for the different type of XML files that will be processed. But I then want to iterate though the code to check for various issues:

foreach (var w in result2)
{
    if (w.CheckIT())
    {
        //do something
    }  
}

我喜欢的是最后一步是在基类中的方法,我可以从每个子类通过变种varible进去。

What I would love is the final step to be in a method in the base class, and I can pass the 'var' varible into it from each child class.

推荐答案

是W 类型 Object1 (在code作为上面写的)。您可以将鼠标悬停在 VAR 关键字和看到,Visual Studio的说明你的提示找到这个自己。

The type of w is Object1 (in the code as written above). You can find this yourself by hovering your mouse over the var keyword and seeing the tooltip that Visual Studio shows you.

这是很难从你的问题告诉,但它听起来像 CheckIt 方法上的一个基本类型 Object1 。如果它是你可以写你的方法来检查它们作为

It's hard to tell from your question, but it sounds like the CheckIt method is defined on a base type of Object1. If it is you can write your method to check them as

protected void CheckAll<T>(IEnumerable<T> result) where T : <base type with CheckIt method>
{
    foreach(var w in result)
    {
        if(w.CheckIt())
        {
            // do something
        }
    }
}

这篇关于传递一个“变种”到另一种方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆