通用类内的属性。在Mongodb的Find中获取属性

时间:2018-08-02 14:26:26

标签: c# mongodb reflection

我正在使用此类:

public class MyClass 
{
    ...
    public string culture { get; set; }
    ...
}

和此功能

object getData<T>() 
{
   var res = GetCollection<T>().Find(x => x.culture == "ca-ES").ToList()

   return res;
}

称其为getData<MyClass>()

GetCollection 函数可以运行,但不是问题:

private IMongoCollection<T> GetCollection<T>()
{
    db.GetCollection<T>("myclass");
}

我的问题是我在内部使用的函数找到了一个比较,以按文化来获取该rss。编译器给我一个错误。该属性位于其他同名类中。

mongo中myclass的

Json 是:

[
    {
      "culture": "ca-ES", ...
    },
    {
      "culture": "es-ES", ...
    },
    {
      "culture": "en-GB", ...
    }
]

在示例中应返回:

{
    "culture": "ca-ES", ...
}

我如何解决它以按文化进行比较?

1 个答案:

答案 0 :(得分:1)

您需要过滤可以使用的类型,以便编译器知道存在culture属性:

object getData<T>() where T : MyClass
{
   var res = GetCollection<T>().Find(x => x.culture == "ca-ES").ToList();

   return res;
}

这并不是非常有用,因为现在getData仅可与MyClass或其后代一起使用。

如果只对MyClass感兴趣,则应该删除通用参数:

object getData()
{
   var res = GetCollection<MyClass>().Find(x => x.culture == "ca-ES").ToList();

   return res;
}

或定义一些具有culture属性的基类/接口:

public interface ISomeInterface
{
    string culture { get; set; }
}

public class MyClass : ISomeInterface

object getData<T>() where T : ISomeInterface
{
   var res = GetCollection<T>().Find(x => x.culture == "ca-ES").ToList();

   return res;
}

请注意,在上述任何一种情况下,当您可以使用objectList<T> getData<T>()时都不应返回List<MyClass> getData()