gpt4 book ai didi

C# - 在 Select 子句中选择可编程属性

转载 作者:太空宇宙 更新时间:2023-11-03 11:16:14 24 4
gpt4 key购买 nike

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

有人要吗?

最佳答案

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

where obj.Name == objectName

您期望的是特定类型,或实现特定接口(interface)的类型,或从特定基类派生的类型。

您的方法应该更像:

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

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

关于C# - 在 Select 子句中选择可编程属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12593021/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com