简体   繁体   中英

Get name of class in C#

I need to get the name of the class that I am currently in. The problem is that I am in a static property. Any idea how I can do this without a reference to this ?

如果你真的想要它,尽管TomTom指出,你可能不需要它:

System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name
System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name

If you are in a static property, you should be able to make the type name a constant.

If you have a static property in a base class that is inherited, and you are trying to determine the type of the child class that you are in, you can't do this with a static property. The reason is that the static property is associated with the base class type, not any base class instance. Use a regular property instead, and use GetType().Name or similar.

以下调用应该为您提供当前类型的名称...

System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name

You can use something like:

public static class MyClass
{
  public static string FullName
  {
    get { return typeof(MyClass).FullName; }
  }
}

The solution is fairly obvious just use MakeGenericMethod with T to get the right instance.

But if you want to know the name of T you cannot use the MakeGenericMethod . Another solution is to add a static class with a generic method:

public static class Helper
{
    public static string GetName<T>()
    {
        Type type = typeof(T);
        Type[] genericArguments = type.GetGenericArguments();
        return string.Format("{0}<{1}>", type.Name, string.Join(",", genericArguments.Select(arg => arg.Name)));
    }
}

No change the property ClassName to

public static string ClassName
{
    get
    {
        return Helper.GetName<Generic<T>>();
    }
}

then you will get the correct generic name, for example a call to Generic<DateTime>.ClassName will return "Generic`1<DateTime>".

System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString() Which is mentioned over and over again, can be wrong if the Type is generic. It will not figure out the generic type.

class Generic<T>
{
    public static string ClassName
    {
        [MethodImpl(MethodImplOptions.NoInlining)]
        get 
        {
            return System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString();
        }
    }
}

Also if you don't use the NoInlining directive your code maybe inlined into the callsite which will definitely not yield the results you are after. The following code will print Generic``1[T] , rather than the particular instantiation it's being called from. The solution is fairly obvious just use MakeGenericMethod with T to get the right instance.

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