简体   繁体   中英

Get the name of a class as a string in C#

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?

You can't use .GetType() without an instance because GetType is a method.

You can get the name from the type though like this:

typeof(Foo).Name

And as pointed out by Chris, if you need the assembly qualified name you can use

typeof(Foo).AssemblyQualifiedName

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 .

You could also do something like this:

Type CLASS = typeof(MyClass);

And then you can just access the name, namespace, etc.

 string CLASS_NAME = CLASS.Name;
 string NAMESPACE = CLASS.Namespace;

Alternatively to using typeof(Foo).ToString() , you could use nameof() :

nameof(Foo)
typeof(Foo).ToString()

Another alternative using reflection, is to use the MethodBase class.

In your example, you could add a static property (or method) that provides you with the info you want. Something like:

class Foo
{
    public static string ClassName
    {
        get
        {
            return MethodBase.GetCurrentMethod().DeclaringType.Name;
        }
    }
}

Which would allow you to use it without generating an instance of the type:

tblBar.Include(Foo.ClassName);

Which at runtime will give you:

tblBar.Include("Foo");

您可以使用DbSet<contact>而不是ObjectSet<contact> ,因此您可以使用lambda作为参数,例如tblBar.Include(a => a.foo)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM