developer tip

유형이 익명인지 테스트하는 방법?

optionbox 2020. 11. 28. 09:08
반응형

유형이 익명인지 테스트하는 방법?


이 질문에 이미 답변이 있습니다.

개체를 HTML 태그로 직렬화하는 다음 메서드가 있습니다. 유형이 익명이 아닌 경우에만이 작업을 수행하고 싶습니다.

private void MergeTypeDataToTag(object typeData)
{
    if (typeData != null)
    {
        Type elementType = typeData.GetType();

        if (/* elementType != AnonymousType */)
        {
            _tag.Attributes.Add("class", elementType.Name);    
        }

        // do some more stuff
    }
}

누군가 이것을 달성하는 방법을 보여줄 수 있습니까?

감사


에서 http://www.liensberger.it/web/blog/?p=191 :

private static bool CheckIfAnonymousType(Type type)
{
    if (type == null)
        throw new ArgumentNullException("type");

    // HACK: The only way to detect anonymous types right now.
    return Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute), false)
        && type.IsGenericType && type.Name.Contains("AnonymousType")
        && (type.Name.StartsWith("<>") || type.Name.StartsWith("VB$"))
        && type.Attributes.HasFlag(TypeAttributes.NotPublic);
}

편집 :
확장 방법이있는 또 다른 링크 : 유형이 익명 유형인지 확인


빠르고 더러운 :

if(obj.GetType().Name.Contains("AnonymousType"))

네임 스페이스가 null인지 확인할 수 있습니다.

public static bool IsAnonymousType(this object instance)
{

    if (instance==null)
        return false;

    return instance.GetType().Namespace == null;
}

글쎄, 오늘날 compiier는 익명 유형을 일반 및 봉인 클래스로 생성합니다. 제네릭 클래스의 전문화는 일종의 상속이기 때문에 역설적 인 조합이 아닐까요? 따라서 이것을 확인할 수 있습니다. 1. 이것은 제네릭 유형입니까? 예 => 2) 정의가 봉인되어 있고 && 공개되지 않습니까? 예 => 3) 정의에 CompilerGeneratedAttribute 특성이 있습니까? 이 세 가지 기준이 함께 참이면 익명 유형이있는 것 같습니다 ... 음 ... 설명 된 모든 메소드에 문제가 있습니다. 다음 버전의 .NET에서 변경 될 수있는 측면을 사용하고 있습니다. 따라서 Microsoft가 IsAnonymous 부울 속성을 Type 클래스에 추가 할 때까지. 우리 모두가 죽기 전에 일어나길 바랍니다 ... 그날까지는 다음과 같이 확인할 수 있습니다.

using System.Runtime.CompilerServices;
using System.Reflection;

public static class AnonymousTypesSupport
{
    public static bool IsAnonymous(this Type type)
    {
        if (type.IsGenericType)
        {
            var d = type.GetGenericTypeDefinition();
            if (d.IsClass && d.IsSealed && d.Attributes.HasFlag(TypeAttributes.NotPublic))
            {
                var attributes = d.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false);
                if (attributes != null && attributes.Length > 0)
                {
                    //WOW! We have an anonymous type!!!
                    return true;
                }
            }
        }
        return false;
    }

    public static bool IsAnonymousType<T>(this T instance)
    {
        return IsAnonymous(instance.GetType());
    }
}

확인 CompilerGeneratedAttributeDebuggerDisplayAttribute.Type

다음은 Anomymous 유형에 대해 컴파일러에서 생성 한 코드입니다.

[CompilerGenerated, DebuggerDisplay(@"\{ a = {a} }", Type="<Anonymous Type>")]
internal sealed class <>f__AnonymousType0<<a>j__TPar>
{
...
}

참고URL : https://stackoverflow.com/questions/2483023/how-to-test-if-a-type-is-anonymous

반응형