English 中文(简体)
How to Process Lambda expressions Passed as Argument Intometh - C# NET 3.5
原标题:How to Process Lambda Expressions Passed as Argument Into Method - C# .NET 3.5

我对Lambda语的认知是个极强的故事,而我可以撰写使用Lambda语(Laurabda LINQ)的密码,Im试图书写我自己的方法,其中要用Lambda语表达几个论点。

背景: I m试图书写一种方法,从字面上来说从纽约的另一种物体类型中回收树木。 我迄今有以下几个方面:

public class TreeItem
{
    public string Id { get; set; }
    public string Text { get; set; }

    public TreeItem Parent { get; protected set; }

    public IList<TreeItem> Children
    {
        get
        {
            // Implementation that returns custom TreeItemCollection type
        }
    }

    public static IList<TreeItem> GetTreeFromObject<T>(IList<T> items,
        Expression<Func<T, string>> id,
        Expression<Func<T, string>> text,
        Expression<Func<T, IList<T>>> childProperty) where T : class
    {
        foreach (T item in items)
        {
           // Errrm!?? What do I do now?
        }

        return null;
    }
}

......可以通过......

IList<TreeItem> treeItems = TreeItem.GetTreeFromObject<Category>(
    categories, c => c.Id, c => c.Name, c => c.ChildCategories);

我可以用扼杀价值观和公正的思考来取代这些表述,但我却试图避免这种说法,因为我想把它做得很强。

我之所以这样做,是因为我有控制,接受一个类型的树木清单,而我有几十种不同的类型,它们都是在像结构这样的树种中,并且不想书写每种类型(遵守德国南盟原则)的恰当换算方法。

我是否这样做? 也许有更好的办法这样做?

最佳回答

不存在诸如“玛尔布达”的表述。 可将“lambda”的表述转换成兼容的代表类型,或“expressionmoto

你们现有的签字方法使用树木,但并不明显需要树木。 代表表格(改动了几个参数名称):

public static IList<TreeItem> GetTreeFromObject<T>(IList<T> items,
    Func<T, string> idSelector,
    Func<T, string> textSelector,
    Func<T, IList<T>> childPropertySelector) where T : class

然后,你可以做这样的事情:

foreach (T item in items)
{
    string id = idSelector(item);
    string text = textSelector(item);
    IList<T> children = childPropertySelector(item);
    // Do whatever you need here
}
问题回答

暂无回答




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签