在C#中获取一个类的名称作为字符串 [英] Get the name of a class as a string in C#
问题描述
有没有办法拿一个类名称并将其转换成C#中的一个字符串?
作为实体框架的一部分,执行查询时,.Include方法将以点分隔的字符串列表加入。我有我想要加入的课程模型,为了重构和未来的代码维护,我希望能够在引用这个类时具有编译时的安全性。
因此,有没有办法可以做到这一点:
class Foo
{
}
tblBar.Include(Foo.GetType()。ToString());
我不认为我可以做GetType()没有一个实例。任何想法?
Include需要一个属性名称,而不是一个类名。因此,它是您想要的属性的名称,而不是其类型的名称。 您可以通过反思来获得这一点。
Is there a way to take a class name and convert it to a string in C#?
As part of the Entity Framework, the .Include method takes in a dot-delimited list of strings to join on when performing a query. I have the class model of what I want to join, and for reasons of refactoring and future code maintenance, I want to be able to have compile-time safety when referencing this class.
Thus, is there a way that I could do this:
class Foo
{
}
tblBar.Include ( Foo.GetType().ToString() );
I don't think I can do GetType() without an instance. Any ideas?
Include requires a property name, not a class name. Hence, it's the name of the property you want, not the name of its type. You can get that with reflection.
这篇关于在C#中获取一个类的名称作为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!