수색…


비고

dynamic 키워드는 컴파일 할 때 유형을 알 수없는 변수를 선언합니다. dynamic 변수에는 모든 값이 포함될 수 있으며 런타임 중에 값 유형이 변경 될 수 있습니다.

"Metaprogramming in .NET"이라는 책에서 언급했듯이 C #에는 dynamic 키워드에 대한 백업 유형이 없습니다.

dynamic 키워드에 의해 활성화되는 기능은 로컬 실행 범위의 사이트 컨테이너에서 CallSite 객체를 생성하고 사용하는 컴파일러 작업의 현명한 집합입니다. 컴파일러는 프로그래머가 CallSite 인스턴스를 통해 동적 객체 참조로 인식하는 것을 관리합니다. 컴파일 타임에 동적 처리를받는 매개 변수, 반환 형식, 필드 및 속성은 동적 사용을 위해 생성되었음을 나타내는 메타 데이터로 표시 될 수 있지만 기본 데이터 형식은 항상 System.Object 입니다.

동적 변수 만들기

dynamic foo = 123;
Console.WriteLine(foo + 234);
// 357    Console.WriteLine(foo.ToUpper())
// RuntimeBinderException, since int doesn't have a ToUpper method

foo = "123";
Console.WriteLine(foo + 234);
// 123234
Console.WriteLine(foo.ToUpper()):
// NOW A STRING

동적 인 반환

using System;

public static void Main()
{
    var value = GetValue();
    Console.WriteLine(value);
    // dynamics are useful!
}

private static dynamic GetValue()
{
    return "dynamics are useful!";
}

속성을 사용하여 동적 객체 만들기

using System;
using System.Dynamic;

dynamic info = new ExpandoObject();
info.Id = 123;
info.Another = 456;

Console.WriteLine(info.Another);
// 456

Console.WriteLine(info.DoesntExist);
// Throws RuntimeBinderException

컴파일 타임에 알 수없는 특정 유형 처리

다음과 같은 결과가 출력됩니다.

class IfElseExample
{
    public string DebugToString(object a)
    {
        if (a is StringBuilder)
        {
            return DebugToStringInternal(a as StringBuilder);
        }
        else if (a is List<string>)
        {
            return DebugToStringInternal(a as List<string>);
        }
        else
        {
            return a.ToString();
        }
    }

    private string DebugToStringInternal(object a)
    {
        // Fall Back
        return a.ToString();
    }

    private string DebugToStringInternal(StringBuilder sb)
    {
        return $"StringBuilder - Capacity: {sb.Capacity}, MaxCapacity: {sb.MaxCapacity}, Value: {sb.ToString()}";
    }

    private string DebugToStringInternal(List<string> list)
    {
        return $"List<string> - Count: {list.Count}, Value: {Environment.NewLine + "\t" + string.Join(Environment.NewLine + "\t", list.ToArray())}";
    }
}

class DynamicExample
{
    public string DebugToString(object a)
    {
        return DebugToStringInternal((dynamic)a);
    }

    private string DebugToStringInternal(object a)
    {
        // Fall Back
        return a.ToString();
    }

    private string DebugToStringInternal(StringBuilder sb)
    {
        return $"StringBuilder - Capacity: {sb.Capacity}, MaxCapacity: {sb.MaxCapacity}, Value: {sb.ToString()}";
    }

    private string DebugToStringInternal(List<string> list)
    {
        return $"List<string> - Count: {list.Count}, Value: {Environment.NewLine + "\t" + string.Join(Environment.NewLine + "\t", list.ToArray())}";
    }
}

동적 인 이점은 처리 할 새 유형을 추가하는 것만으로 새로운 유형의 DebugToStringInternal 오버로드를 추가해야한다는 것입니다. 또한 유형에 수동으로 캐스팅 할 필요가 없습니다.



Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow