在C#中获取一个类的名称作为字符串 [英] Get the name of a class as a string in C#

查看:787
本文介绍了在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆