我想创建一个通用的查找方法,您可以在其中指定对象的类型和其他一些识别参数,然后该方法返回该类型的对象。这可能吗?
我在想这样的事情。
public T GetObjectOfType(Guid ID, typeof(T Class))
{
//lookup this object and return it as type safe
}
我知道这是行不通的,但我希望它能解释这个概念
最佳答案
您可以为此使用通用方法:
public T GetObjectOfType<T>(Guid id) where T: class, new()
{
if (id == FooGuid) //some known identifier
{
T t= new T(); //create new or look up existing object here
//set some other properties based on id?
return t;
}
return null;
}
如果您只想创建特定类型的实例,则不需要附加的id参数,我假设您想基于id设置一些属性等。此外,您的类还必须提供默认的构造函数,因此要使用
new()
约束。关于c# - 通用查找方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6352656/