Sugerir traducción
 
Otros han sugerido:

progress indicator
No hay más sugerencias.
Evaluar y enviar comentarios
Contraer todo/Expandir todo Contraer todo
Ver contenido:  en paraleloVer contenido: en paralelo
Visual Studio 2010 - Visual C#
dynamic (C# Reference)

The dynamic type enables the operations in which it occurs to bypass compile-time type checking. Instead, these operations are resolved at run time. The dynamic type simplifies access to COM APIs such as the Office Automation APIs, and also to dynamic APIs such as IronPython libraries, and to the HTML Document Object Model (DOM).

Type dynamic behaves like type object in most circumstances. However, operations that contain expressions of type dynamic are not resolved or type checked by the compiler. The compiler packages together information about the operation, and that information is later used to evaluate the operation at run time. As part of the process, variables of type dynamic are compiled into variables of type object. Therefore, type dynamic exists only at compile time, not at run time.

The following example contrasts a variable of type dynamic to a variable of type object. To verify the type of each variable at compile time, place the mouse pointer over dyn or obj in the WriteLine statements. IntelliSense shows dynamic for dyn and object for obj.

C#
class Program
{
    static void Main(string[] args)
    {
        dynamic dyn = 1;
        object obj = 1;

        // Rest the mouse pointer over dyn and obj to see their
        // types at compile time.
        System.Console.WriteLine(dyn.GetType());
        System.Console.WriteLine(obj.GetType());
    }
}

The WriteLine statements display the run-time types of dyn and obj. At that point, both have the same type, integer. The following output is produced:

System.Int32

System.Int32

To see the difference between dyn and obj at compile time, add the following two lines between the declarations and the WriteLine statements in the previous example.

C#
dyn = dyn + 3;
obj = obj + 3;

A compiler error is reported for the attempted addition of an integer and an object in expression obj + 3. However, no error is reported for dyn + 3. The expression that contains dyn is not checked at compile time because the type of dyn is dynamic.

The dynamic keyword can appear directly or as a component of a constructed type in the following situations:

  • In declarations, as the type of a property, field, indexer, parameter, return value, local variable, or type constraint. The following class definition uses dynamic in several different declarations.

    C#
    class ExampleClass
    {
        // A dynamic field.
        static dynamic field;
    
        // A dynamic property.
        dynamic prop { get; set; }
    
        // A dynamic return type and a dynamic paramater type.
        public dynamic exampleMethod(dynamic d)
        {
            // A dynamic local variable.
            dynamic local = "Local variable";
            int two = 2;
    
            if (d is int)
            {
                return local;
            }
            else
            {
                return two;
            }
        }
    }
    
  • In explicit type conversions, as the target type of a conversion.

    C#
    static void convertToDynamic()
    {
        dynamic d;
        int i = 20;
        d = (dynamic)i;
        Console.WriteLine(d);
    
        string s = "Example string.";
        d = (dynamic)s;
        Console.WriteLine(d);
    
        DateTime dt = DateTime.Today;
        d = (dynamic)dt;
        Console.WriteLine(d);
    
    }
    // Results:
    // 20
    // Example string.
    // 2/17/2009 9:12:00 AM
    
  • In any context where types serve as values, such as on the right side of an is operator or an as operator, or as the argument to typeof as part of a constructed type. For example, dynamic can be used in the following expressions.

    C#
    int i = 8;
    dynamic d;
    // With the is operator.
    // The dynamic type behaves like object. The following
    // expression returns true unless someVar has the value null.
    if (someVar is dynamic) { }
    
    // With the as operator.
    d = i as dynamic;
    
    // With typeof, as part of a constructed type.
    Console.WriteLine(typeof(List<dynamic>));
    
    // The following statement causes a compiler error.
    //Console.WriteLine(typeof(dynamic));
    

The following example uses dynamic in several declarations. The Main method also contrasts compile-time type checking with run-time type checking.

C#
using System;

namespace DynamicExamples
{
    class Program
    {
        static void Main(string[] args)
        {
            ExampleClass ec = new ExampleClass();
            Console.WriteLine(ec.exampleMethod(10));
            Console.WriteLine(ec.exampleMethod("value"));

            // The following line causes a compiler error because exampleMethod
            // takes only one argument.
            //Console.WriteLine(ec.exampleMethod(10, 4));

            dynamic dynamic_ec = new ExampleClass();
            Console.WriteLine(dynamic_ec.exampleMethod(10));

            // Because dynamic_ec is dynamic, the following call to exampleMethod
            // with two arguments does not produce an error at compile time.
            // However, itdoes cause a run-time error. 
            //Console.WriteLine(dynamic_ec.exampleMethod(10, 4));
        }
    }

    class ExampleClass
    {
        static dynamic field;
        dynamic prop { get; set; }

        public dynamic exampleMethod(dynamic d)
        {
            dynamic local = "Local variable";
            int two = 2;

            if (d is int)
            {
                return local;
            }
            else
            {
                return two;
            }
        }
    }
}
// Results:
// Local variable
// 2
// Local variable

For more information and examples, see Using Type dynamic (C# Programming Guide).

Visual Studio 2010 - Visual C#
dynamic (Referencia de C#)

El tipo dynamic permite que las operaciones en las que se produce omitan la comprobación de tipo en tiempo de compilación. En su lugar, se resuelven estas operaciones en tiempo de ejecución. El tipo dynamic simplifica el acceso a API de COM tales como las API de automatización de Office y también a API dinámicas como las bibliotecas de IronPython, y al Modelo de objetos documentos (DOM) HTML.

El tipo dynamic se comporta como el tipo object en la mayoría de las circunstancias. Sin embargo, el compilador no resuelve o no comprueba el tipo de las operaciones que contienen expresiones de tipo dynamic. El compilador empaqueta información sobre la operación y esa información se utiliza después para evaluar la operación en tiempo de ejecución. Como parte del proceso, las variables de tipo dynamic están compiladas en las variables de tipo object. Por consiguiente, el tipo dynamic sólo existe en tiempo de compilación, no en tiempo de ejecución.

El siguiente ejemplo contrasta una variable de tipo dynamic con una variable de tipo object. Para comprobar el tipo de cada variable en tiempo de compilación, coloque el puntero del mouse sobre dyn u obj en las instrucciones WriteLine. IntelliSense muestra dynamic para dyn y object para obj.

C#
class Program
{
    static void Main(string[] args)
    {
        dynamic dyn = 1;
        object obj = 1;

        // Rest the mouse pointer over dyn and obj to see their
        // types at compile time.
        System.Console.WriteLine(dyn.GetType());
        System.Console.WriteLine(obj.GetType());
    }
}

Las instrucciones WriteLine muestran los tipos en tiempo de ejecución de dyn y obj. En ese punto, ambos tiene el mismo tipo, entero. Se produce el siguiente resultado:

System.Int32

System.Int32

Para ver la diferencia entre dyn y obj en tiempo de compilación, agregue las dos líneas siguientes entre las declaraciones y las instrucciones WriteLine en el ejemplo anterior.

C#
dyn = dyn + 3;
obj = obj + 3;

Un error del compilador se notifica para el intento de suma de un entero y un objeto en la expresión obj + 3. Sin embargo, no se notifica ningún error para dyn + 3. En tiempo de compilación no se comprueba la expresión que contiene dyn porque el tipo de dyn es dynamic.

La palabra clave dynamic puede aparecer directamente o como un componente de un tipo construido en las siguientes situaciones:

  • En declaraciones, como el tipo de una propiedad, un campo, un indizador, un parámetro, un valor devuelto, una variable local o una restricción de tipo. La siguiente definición de clase utiliza dynamic en varias declaraciones diferentes.

    C#
    class ExampleClass
    {
        // A dynamic field.
        static dynamic field;
    
        // A dynamic property.
        dynamic prop { get; set; }
    
        // A dynamic return type and a dynamic paramater type.
        public dynamic exampleMethod(dynamic d)
        {
            // A dynamic local variable.
            dynamic local = "Local variable";
            int two = 2;
    
            if (d is int)
            {
                return local;
            }
            else
            {
                return two;
            }
        }
    }
    
  • En conversiones de tipos explícitas, como tipo de destino de una conversión.

    C#
    static void convertToDynamic()
    {
        dynamic d;
        int i = 20;
        d = (dynamic)i;
        Console.WriteLine(d);
    
        string s = "Example string.";
        d = (dynamic)s;
        Console.WriteLine(d);
    
        DateTime dt = DateTime.Today;
        d = (dynamic)dt;
        Console.WriteLine(d);
    
    }
    // Results:
    // 20
    // Example string.
    // 2/17/2009 9:12:00 AM
    
  • En cualquier contexto donde los tipos actúen como valores, por ejemplo, en el lado derecho de un operador is o un operador as, o como argumento de typeof como parte de un tipo construido. Por ejemplo, se puede usar dynamic en las siguientes expresiones.

    C#
    int i = 8;
    dynamic d;
    // With the is operator.
    // The dynamic type behaves like object. The following
    // expression returns true unless someVar has the value null.
    if (someVar is dynamic) { }
    
    // With the as operator.
    d = i as dynamic;
    
    // With typeof, as part of a constructed type.
    Console.WriteLine(typeof(List<dynamic>));
    
    // The following statement causes a compiler error.
    //Console.WriteLine(typeof(dynamic));
    

El ejemplo siguiente usa dynamic en varias declaraciones. El método Main también contrasta la comprobación de tipo en tiempo de compilación con la comprobación de tipo en tiempo de ejecución.

C#
using System;

namespace DynamicExamples
{
    class Program
    {
        static void Main(string[] args)
        {
            ExampleClass ec = new ExampleClass();
            Console.WriteLine(ec.exampleMethod(10));
            Console.WriteLine(ec.exampleMethod("value"));

            // The following line causes a compiler error because exampleMethod
            // takes only one argument.
            //Console.WriteLine(ec.exampleMethod(10, 4));

            dynamic dynamic_ec = new ExampleClass();
            Console.WriteLine(dynamic_ec.exampleMethod(10));

            // Because dynamic_ec is dynamic, the following call to exampleMethod
            // with two arguments does not produce an error at compile time.
            // However, itdoes cause a run-time error. 
            //Console.WriteLine(dynamic_ec.exampleMethod(10, 4));
        }
    }

    class ExampleClass
    {
        static dynamic field;
        dynamic prop { get; set; }

        public dynamic exampleMethod(dynamic d)
        {
            dynamic local = "Local variable";
            int two = 2;

            if (d is int)
            {
                return local;
            }
            else
            {
                return two;
            }
        }
    }
}
// Results:
// Local variable
// 2
// Local variable

Para obtener más información y ejemplos, vea Uso de tipo dinámico (Guía de programación de C#).

Contenido de la comunidad   ¿Qué es Community Content?
Agregar contenido nuevo RSS  Anotaciones
Processing
© 2012 Microsoft. Reservados todos los derechos. Términos de uso | Marcas Registradas | Privacidad
Page view tracker