问题描述
好了,所以我试图做一个漂亮的超类,可生成TSQL查询来搜索所有子类的公共字符串属性的数据访问对象。我想使用反射来获取子类的类型,然后通过所有的对象上的公共串属性的迭代,因为这些属性名称是相同的数据库列名。然后,我可以使用这些属性名称生成TSQL查询。
Ok, so I'm trying to make a nice superclass for data-access objects that can generate a tsql query to search all of the subclass's public string properties. I want to use reflection to get the type of the subclass and then iterate through all of the public string properties on the object, since those property names are the same as the database column names. Then I can use those property names to generate a tsql query.
[警告:哎,ID,而使用NHibernate的,但没有办法,我能说服这些家伙使用]
[caveat: hey, id rather use nhibernate but no way I could convince these guys to use that]
[我也可以和仿制药解决这个问题,但我认为他们发现泛型可怕的,因为他们是VB.net人(对不起,如果我伤害了你的感情VB.net一瞥;()]
[Also I could solve this with generics, but I think they find generics scary because they are VB.net guys, (sorry if I hurt your feelings VB.net peeps ;( )]
确定这样的基本对象是这样的:
Ok so the base object is something like this:
public abstract class RepositoryBase
{
public static IList<RepositoryBase> Search()
{
//get all public properties of the inheriting subclass
// I already have the rest of the search code
}
}
这甚至可能,或建议?
Is this even possible, or advisable?
虽然我打字这一点,我很喜欢拧,我就做它的仿制药。
While I was typing this, I was like "screw it, I'll just do it with generics".
感谢您的阅读!
推荐答案
在所谓的内经派生类的静态方法,编译器解析方法使IL实际上包含的基类。例如:
When you call a static method "via" a derived class, the compiler resolves the method so the IL actually contains the base class. For instance:
public class Base
{
static void Foo() {}
}
public class Derived : Base {}
class Test
{
static void Main()
{
Derived.Foo();
}
}
在主的通话将实际上最终编译为Base.Foo()中的白细胞介素(从C#编译为最少的时候)。所以,你不能告诉在执行时是什么原来的呼叫了。
The call in Main will actually end up compiled as Base.Foo() in the IL (as least when compiled from C#). So you can't tell at execution time what the original call was.
这听起来像泛型是要走的路。
It does sound like generics is the way to go.
这篇关于如何获取子类类型的对象在.NET中的静态超功能,使用反射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!