IT

전체 네임 스페이스없이 유형 이름 가져 오기

lottoking 2020. 3. 27. 08:13
반응형

전체 네임 스페이스없이 유형 이름 가져 오기


다음 코드가 있습니다.

return "[Inserted new " + typeof(T).ToString() + "]";

그러나

 typeof(T).ToString()

네임 스페이스를 포함한 전체 이름을 반환

어쨌든 클래스 이름을 얻는 방법이 있습니까 (네임 스페이스 한정자가 없습니까?)


typeof(T).Name // class name, no namespace
typeof(T).FullName // namespace and class name
typeof(T).Namespace // namespace, no class name

제네릭 형식에 대한 형식 매개 변수를 얻으려면 다음을 시도하십시오.

public static string CSharpName(this Type type)
{
    var sb = new StringBuilder();
    var name = type.Name;
    if (!type.IsGenericType) return name;
    sb.Append(name.Substring(0, name.IndexOf('`')));
    sb.Append("<");
    sb.Append(string.Join(", ", type.GetGenericArguments()
                                    .Select(t => t.CSharpName())));
    sb.Append(">");
    return sb.ToString();
}

아마도 재귀로 인해 가장 좋은 해결책은 아니지만 작동합니다. 출력은 다음과 같습니다.

Dictionary<String, Object>

( 유형 속성 )을 사용하십시오

 Name   Gets the name of the current member. (Inherited from MemberInfo.)
 Example : typeof(T).Name;

typeof (T). 이름;


C # 6.0 (포함) 후에는 nameof expression을 사용할 수 있습니다 .

using Stuff = Some.Cool.Functionality  
class C {  
    static int Method1 (string x, int y) {}  
    static int Method1 (string x, string y) {}  
    int Method2 (int z) {}  
    string f<T>() => nameof(T);  
}  

var c = new C()  

nameof(C) -> "C"  
nameof(C.Method1) -> "Method1"   
nameof(C.Method2) -> "Method2"  
nameof(c.Method1) -> "Method1"   
nameof(c.Method2) -> "Method2"  
nameof(z) -> "z" // inside of Method2 ok, inside Method1 is a compiler error  
nameof(Stuff) = "Stuff"  
nameof(T) -> "T" // works inside of method but not in attributes on the method  
nameof(f) -> “f”  
nameof(f<T>) -> syntax error  
nameof(f<>) -> syntax error  
nameof(Method2()) -> error “This expression does not have a name”  

노트! nameof기본 객체의 런타임 유형을 얻지 못하면 컴파일 타임 인수 일뿐입니다. 메소드가 IEnumerable을 허용하면 nameof는 단순히 "IEnumerable"을 리턴하지만 실제 오브젝트는 "List"일 수 있습니다.


가장 좋은 방법 :

obj.GetType().BaseType.Name

참고 URL : https://stackoverflow.com/questions/3396300/get-type-name-without-full-namespace

반응형