2

请原谅我在问这个问题时的无知,因为我还在学习 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 型对象的属性的项目。

有接盘侠吗?

4

1 回答 1

2

问题是您正在编写一个泛型方法,这意味着它将接受任何类型 T。但实际上,当您编写时:

where obj.Name == objectName

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

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

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

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

于 2012-09-26T00:49:19.187 回答