【问题标题】:C# - Select programmable attribute in Select clauseC# - 在 Select 子句中选择可编程属性
【发布时间】:2012-09-17 13:33:35
【问题描述】:

请原谅我在问这个问题时的无知,因为我还在学习 NHibernate 和 Linq。我做了一些搜索,但我不明白如何或是否可以解决我的问题

我有以下代码块:

// this function searches the database's table for a single object that matches the 'Name' property with 'objectName'
public static Object Read<T>(string objectName)
{
    using (ISession session = NHibernateHelper.OpenSession())
    {
        IQueryable<T> objectList = session.Query<T>(); // pull (query) all the objects from the table in the database
        int count = objectList.Count(); // return the number of objects in the table
        // alternative: int count = makeList.Count<T>();

        IQueryable<T> objectQuery = null; // create a reference for our queryable list of objects
        object foundObject = null; // create an object reference for our found object

        if (count > 0)
        {
            // give me all objects that have a name that matches 'objectName' and store them in 'objectQuery'
            objectQuery = (from obj in objectList where obj.Name == objectName select obj);

            // make sure that 'objectQuery' has only one object in it
            try
            {
                foundObject = objectQuery.Single();
            }
            catch
            {
                return null;
            }

            // output some information to the console (output screen)
            Console.WriteLine("Read Make: " + foundObject.ToString());
        }
        // pass the reference of the found object on to whoever asked for it
        return foundObject;
    }
}

这一切都很好,除了一行: objectQuery = (from obj in objectList where obj.Name == objectName select obj);

这里的问题是我要求一个未知对象的“名称”属性,这不仅是不可能的,而且是错误的代码。

我真正想做的是指定我正在寻找具有属于 T 型对象的属性的项目。

有接受者吗?

【问题讨论】:

    标签: c# linq generics iqueryable


    【解决方案1】:

    问题是你在写一个泛型方法,这意味着它可以接受任何类型的T。但实际上,当你写的时候:

    where obj.Name == objectName
    

    您期望一个特定类型,或实现特定接口的类型,或派生自特定基类。

    你的方法应该看起来更像:

    public static T Read<T>(string objectName)
    where T : ISomeInterface
    

    注意,我还把返回类型从 Object 改成了 T,这样对这个方法的调用者更加友好,避免了他们将 Object 强制转换为 T 的需要。

    【讨论】:

    • 感谢您对返回类型的改进。这为我解决了一些麻烦!您能否详细说明 ISomeInterface 的使用?我真的很感激。
    • 请忽略我的详细说明。我想我可以处理这部分。非常感谢!
    • @Kashif,没问题。如果您认为答案正确,您能否将答案标记为已接受?
    • 我还有一个问题,这是我遇到的根本问题。我已将代码行更改为:objectQuery = (from obj in objectList where obj.Equals(objectName) select obj);,但返回的对象不是 T 类型。事实上,它返回一个布尔值。我在这里做错了什么?
    • 对于任何关注这篇文章的人。根本问题可以在这里解决:stackoverflow.com/a/12610826/1055723
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-28
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    • 1970-01-01
    • 1970-01-01
    • 2018-02-11
    相关资源
    最近更新 更多