是否可以在C#中的嵌套类中查找(通用)具有GUID的对象? [英] Is it possible to find(generically) an object with a GUID in a nested Class in C#?

查看:113
本文介绍了是否可以在C#中的嵌套类中查找(通用)具有GUID的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有嵌套类,例如



订单

 code> ID,(GUID = 8e6e48f7-9047-4e2a-95e7-ec4318641fbb)
日期
订单 - > List< OrderItem>

订单项

  ID,(GUID = = 4582234b-d8b5-4665-b00f-e4f09ff3e2c6)
ProductId
数量
单位
价格
ID,(GUID = = b0d12322-e92c-42c6-b2b7-520db1d3a818)
ProductId
数量
单位
价格
pre>

因为我有嵌套,我使用GUID作为我的对象的ID,我想知道是否有一个通用的方法来找到一个给定GUID的对象。一个我有这个对象,然后可以从它的父列表中删除它。



顺便说一下,我意识到,我可以使用特定的lambda表达式获得特定的对象,但这会导致许多不同情况下的许多表达式,因此很多人对一个通用方法感兴趣。



谢谢,

解决方案

我可能会创建一个接口,所有的类(或基类)将实现调用 IGuidSearchable 中。它需要设置两个属性,ID和 List< ISearchable> Children 集合。实现类可以使用这个或者负责设置这个属性等于它们使用的属性(例如在你的例子中 Orders - > List< OrderItem>

  public static IGuidSearchable FindObjectByGuid(this IGuidSearchable source,System.Guid guid)
{
if source.ID.Equals(guid))
{
return source;
}
foreach(source.Children中的可搜索子项)
{
if(child.FindObjectByGuid(guid)!= null)
return child;
}

return null; // Fall through
}


I have nested classes ie

Order

ID, (GUID = 8e6e48f7-9047-4e2a-95e7-ec4318641fbb)
Date
Orders -> List<OrderItem>

OrderItem

ID, (GUID= = 4582234b-d8b5-4665-b00f-e4f09ff3e2c6)
ProductId
Qty
Unit
Price
ID, (GUID= = b0d12322-e92c-42c6-b2b7-520db1d3a818)
ProductId
Qty
Unit
Price

Because I have nesting and I am using GUIDs as IDs for my objects, I am wondering whether there is a generic method to find an object given a GUID. One I have this object I could then remove it from it parent list.

By the way, I do realise that I could used specific lambda expression to get at the specific objects, but this would result in many expressions for many different scenarios, hence many interest in one generic approach.

Thanks,

解决方案

I would probably create an interface that all of my classes (or base classes) would implement called IGuidSearchable or something like that. It would need to set two properties, the ID and a Children collection of List<ISearchable>. The implementing classes could either use this or would be responsible for setting this property to be equal to the property they use (like Orders -> List<OrderItem> in your example).

public static IGuidSearchable FindObjectByGuid(this IGuidSearchable source, System.Guid guid) 
{
    if (source.ID.Equals(guid)) 
    {
        return source;
    }
    foreach (ISearchable child in source.Children)
    {
        if (child.FindObjectByGuid(guid) != null)
            return child;            
    }   

    return null; // Fall through    
}

这篇关于是否可以在C#中的嵌套类中查找(通用)具有GUID的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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