泛化函数以在单个 class 中从多个 IList 中删除实体

generalize function to delete entity from multiple IList in single class

我有一个 class 有多个列表,即 CityStateCountry 作为 class 的成员,现在我想制作一个泛化函数,其中 用户可以传递国家或州或城市的 ID,它将删除该特定记录。我通过对每个 class 实现 IEntity 接口来共同化元素,即 id,这样我就可以根据 id 删除特定的城市、国家和州,这样我就可以执行 deleteDataFromNotification<City>("23323")

但是这里的问题是IList。有没有办法创建这样一个接受 MatserInfo 并自动获取所需列表并删除实体的函数。

类似的东西,其中 getEntityList 自动获取列表

var data = realm.All<MasterInfo>().getEntityList().Where(d => d.id == id).FirstOrDefault();

以下是我的代码

void deleteData<T>(String id) where T : RealmObject, IEntity{

            Realm realm = Realm.GetInstance();

            try
            {
                var data = realm.All<T>().Where(d => d.id == id).FirstOrDefault();

                realm.WriteAsync(tempRealm =>
                {

                    if (data != null)
                        tempRealm.Remove(data);
                });
            }
            catch (Exception e)
            {

                Debug.WriteLine("Exception " + e.Message);
            }

}

public class MasterInfo : RealmObject {

    [JsonProperty("listCityMaster", NullValueHandling = NullValueHandling.Ignore)]
    public IList<City> cityList { get; }

    [JsonProperty("listStateMaster", NullValueHandling = NullValueHandling.Ignore)]
    public IList<State> stateList { get; }

    [JsonProperty("listCountryMaster", NullValueHandling = NullValueHandling.Ignore)]
    public IList<Country> countryList { get; }

}

public  class Country : RealmObject,IEntity
{

    [PrimaryKey]
    public String id { get; set; }
    public String name { get; set; }
}

public class State : RealmObject,IEntity
{

    public String countryId { get; set; }
    [PrimaryKey]
    public String id { get; set; }
    public String name { get; set; }

}

 public class City : RealmObject,IEntity
{

    public String countryId { get; set; }
    [PrimaryKey]
    public String id { get; set; }
    public String name { get; set; }
    public String stateId { get; set; }


}

 public interface IEntity
{

     String id { get; set; }
}

对于显示的示例,您可以在 MasterInfo class 中实现 GetEntityList<T>,如下所示。如所写,如果使用不匹配的类型调用,这将 return 为 null,而不是错误。

public IList<T> GetEntityList<T>()
{
    return (cityList as IList<T>) ?? (stateList as IList<T>) ?? (countryList as IList<T>);
}

编辑:显示更动态的方式。

此版本创建了一个实现 IList 的属性列表,并将 属性 getter 缓存在静态字典变量中。当您调用 GetEntityList 时,它使用适当的 getter 到 return 匹配列表。

获取匹配属性的反射是运行一次,当你的应用程序第一次执行这段代码时。每当您调用 GetEntityList.

时,都会执行获取 属性 值的反射
static Dictionary<Type, PropertyInfo> DictionaryOfILists = typeof(MasterInfo)
    .GetProperties()
    .Where(v => v.PropertyType.IsGenericType && v.PropertyType.GetGenericTypeDefinition() == typeof(IList<>))
    .ToDictionary(v => v.PropertyType, v => v);

public IList<T> GetEntityList<T>()
{
    return DictionaryOfILists[typeof(IList<T>)].GetValue(this) as IList<T>;
}