Visual Studio 2010 - Visual C# Using Type dynamic (C# Programming Guide) Visual C# 2010 introduces a new type, dynamic. The type is a static type, but an object of type dynamic bypasses static type checking. In most cases, it functions like it has type object. At compile time, an element that is typed as dynamic is assumed to support any operation. Therefore, you do not have to be concerned about whether the object gets its value from a COM API, from a dynamic language such as IronPython, from the HTML Document Object Model (DOM), from reflection, or from somewhere else in the program. However, if the code is not valid, errors are caught at run time. For example, if instance method exampleMethod1 in the following code has only one parameter, the compiler recognizes that the first call to the method, ec.exampleMethod1(10, 4), is not valid because it contains two arguments. The call causes a compiler error. The second call to the method, dynamic_ec.exampleMethod1(10, 4), is not checked by the compiler because the type of dynamic_ec is dynamic. Therefore, no compiler error is reported. However, the error does not escape notice indefinitely. It is caught at run time and causes a run-time exception.
static void Main(string[] args)
{
ExampleClass ec = new ExampleClass();
// The following line causes a compiler error if exampleMethod1 has only
// one parameter.
//ec.exampleMethod1(10, 4);
dynamic dynamic_ec = new ExampleClass();
// The following line is not identified as an error by the
// compiler, but it causes a run-time exception.
dynamic_ec.exampleMethod1(10, 4);
// The following calls also do not cause compiler errors, whether
// appropriate methods exist or not.
dynamic_ec.someMethod("some argument", 7, null);
dynamic_ec.nonexistentMethod();
}
class ExampleClass
{
public ExampleClass() { }
public ExampleClass(int v) { }
public void exampleMethod1(int i) { }
public void exampleMethod2(string str) { }
}
The role of the compiler in these examples is to package together information about what each statement is proposing to do to the object or expression that is typed as dynamic. At run time, the stored information is examined, and any statement that is not valid causes a run-time exception. The result of most dynamic operations is itself dynamic. For example, if you rest the mouse pointer over the use of testSum in the following example, IntelliSense displays the type (local variable) dynamic testSum.
dynamic d = 1;
var testSum = d + 3;
// Rest the mouse pointer over testSum in the following statement.
System.Console.WriteLine(testSum);
Operations in which the result is not dynamic include conversions from dynamic to another type, and constructor calls that include arguments of type dynamic. For example, the type of testInstance in the following declaration is ExampleClass, not dynamic.
var testInstance = new ExampleClass(d);
Conversion examples are shown in the following section, "Conversions."

Conversions
Conversions between dynamic objects and other types are easy. This enables the developer to switch between dynamic and non-dynamic behavior. Any object can be converted to dynamic type implicitly, as shown in the following examples.
dynamic d1 = 7;
dynamic d2 = "a string";
dynamic d3 = System.DateTime.Today;
dynamic d4 = System.Diagnostics.Process.GetProcesses();
Conversely, an implicit conversion can be dynamically applied to any expression of type dynamic.
int i = d1;
string str = d2;
DateTime dt = d3;
System.Diagnostics.Process[] procs = d4;

Overload Resolution with Arguments of Type dynamic
Overload resolution occurs at run time instead of at compile time if one or more of the arguments in a method call have the type dynamic, or if the receiver of the method call is of type dynamic. In the following example, if the only accessible exampleMethod2 method is defined to take a string argument, sending d1 as the argument does not cause a compiler error, but it does cause a run-time exception. Overload resolution fails at run time because the run-time type of d1 is int, and exampleMethod2 requires a string.
// Valid.
ec.exampleMethod2("a string");
// The following statement does not cause a compiler error, even though ec is not
// dynamic. A run-time exception is raised because the run-time type of d1 is int.
ec.exampleMethod2(d1);
// The following statement does cause a compiler error.
//ec.exampleMethod2(7);

Dynamic Language Runtime
The dynamic language runtime (DLR) is a new API in .NET Framework 4. It provides the infrastructure that supports the dynamic type in C#, and also the implementation of dynamic programming languages such as IronPython and IronRuby. For more information about the DLR, see Dynamic Language Runtime Overview.

COM Interop
Visual C# 2010 includes several features that improve the experience of interoperating with COM APIs such as the Office Automation APIs. Among the improvements are the use of the dynamic type, and of named and optional arguments. Many COM methods allow for variation in argument types and return type by designating the types as object. This has necessitated explicit casting of the values to coordinate with strongly typed variables in C#. If you compile by using the /link (C# Compiler Options) option, the introduction of the dynamic type enables you to treat the occurrences of object in COM signatures as if they were of type dynamic, and thereby to avoid much of the casting. For example, the following statements contrast how you access a cell in a Microsoft Office Excel spreadsheet with the dynamic type and without the dynamic type.
// Before the introduction of dynamic.
((Excel.Range)excelApp.Cells[1, 1]).Value2 = "Name";
Excel.Range range2008 = (Excel.Range)excelApp.Cells[1, 1];
// After the introduction of dynamic, the access to the Value property and
// the conversion to Excel.Range are handled by the run-time COM binder.
excelApp.Cells[1, 1].Value = "Name";
Excel.Range range2010 = excelApp.Cells[1, 1];

Related Topics
|
Visual Studio 2010 - Visual C# Verwenden des Typs dynamic (C#-Programmierhandbuch) Visual C# 2010 stellt den neuen Typ dynamic bereit. Es handelt sich zwar um einen statischen Typ, aber ein Objekt des Typs dynamic umgeht die Überprüfung statischer Typen. Die Funktionsweise stimmt in den meisten Fällen mit der des Typs object überein. Zur Kompilierzeit wird davon ausgegangen, dass ein Element vom Typ dynamic jeden beliebigen Vorgang unterstützt. Aus diesem Grund müssen Sie sich keine Gedanken darüber machen, ob der Wert des Objekts von einer COM-API, von einer dynamischen Sprache wie IronPython, vom HTML-Dokumentobjektmodell (DOM), durch Reflektion oder von einem anderen Element im Programm abgerufen wird. Wenn der Code jedoch nicht gültig ist, werden zur Laufzeit Fehler abgefangen. Beispiel: Wenn die Instanzmethode exampleMethod1 im folgenden Code nur einen Parameter aufweist, erkennt der Compiler den ersten Aufruf der Methode, ec.exampleMethod1(10, 4), als nicht gültig, weil darin zwei Argumente enthalten sind. Der Aufruf löst einen Compilerfehler aus. Der zweite Aufruf der Methode, dynamic_ec.exampleMethod1(10, 4), wird nicht vom Compiler überprüft, da der Typ von dynamic_ec dynamic ist. Somit wird kein Compilerfehler gemeldet. Der Fehler wird jedoch nicht unendlich verborgen. Er wird zur Laufzeit abgefangen und löst eine Laufzeitausnahme aus.
static void Main(string[] args)
{
ExampleClass ec = new ExampleClass();
// The following line causes a compiler error if exampleMethod1 has only
// one parameter.
//ec.exampleMethod1(10, 4);
dynamic dynamic_ec = new ExampleClass();
// The following line is not identified as an error by the
// compiler, but it causes a run-time exception.
dynamic_ec.exampleMethod1(10, 4);
// The following calls also do not cause compiler errors, whether
// appropriate methods exist or not.
dynamic_ec.someMethod("some argument", 7, null);
dynamic_ec.nonexistentMethod();
}
class ExampleClass
{
public ExampleClass() { }
public ExampleClass(int v) { }
public void exampleMethod1(int i) { }
public void exampleMethod2(string str) { }
}
Die Rolle des Compilers in diesen Beispielen besteht darin, Informationen zu den Vorgängen zusammenzufassen, die die einzelnen Anweisungen für das Objekt oder den Ausdruck vom Typ dynamic vorsehen. Zur Laufzeit werden die gespeicherten Informationen geprüft, und nicht gültige Anweisungen lösen eine Laufzeitausnahme aus. Das Ergebnis der meisten dynamischen Vorgänge ist ebenfalls dynamic. Wenn Sie z. B. im folgenden Beispiel mit der Maus auf die Verwendung von testSum zeigen, zeigt IntelliSense den Typ (lokale Variable) dynamic testSum an.
dynamic d = 1;
var testSum = d + 3;
// Rest the mouse pointer over testSum in the following statement.
System.Console.WriteLine(testSum);
Zu den Vorgängen, bei denen das Ergebnis nicht dynamic ist, zählen Konvertierungen von dynamic in einen anderen Typ sowie Konstruktoraufrufe, die Argumente vom Typ dynamic einschließen. Beispiel: Der Typ von testInstance in der folgenden Deklaration ist ExampleClass, nicht dynamic.
var testInstance = new ExampleClass(d);
Konvertierungsbeispiele werden im folgenden Abschnitt "Konvertierungen" gezeigt.

Konvertierungen
Konvertierungen zwischen dynamischen Objekten und anderen Typen sind einfach. So können Entwickler zwischen dynamischem und nicht dynamischem Verhalten wechseln. Jedes beliebige Objekt kann implizit in den dynamic-Typ konvertiert werden, wie in den folgenden Beispielen gezeigt.
dynamic d1 = 7;
dynamic d2 = "a string";
dynamic d3 = System.DateTime.Today;
dynamic d4 = System.Diagnostics.Process.GetProcesses();
Ebenso kann eine implizite Konvertierung dynamisch auf jeden beliebigen Ausdruck vom Typ dynamic angewendet werden.
int i = d1;
string str = d2;
DateTime dt = d3;
System.Diagnostics.Process[] procs = d4;

Überladungsauflösung mit Argumenten vom Typ dynamic
Die Überladungsauflösung tritt zur Laufzeit statt zur Kompilierzeit auf, wenn mindestens eines der Argumente in einem Methodenaufruf den Typ dynamic aufweist, oder wenn der Empfänger des Methodenaufrufs den Typ dynamic aufweist. Wenn im folgenden Beispiel die einzige zugreifbare exampleMethod2-Methode so definiert wird, dass sie ein Zeichenfolgenargument erfordert, löst das Senden von d1 als Argument keinen Compilerfehler, aber eine Laufzeitausnahme aus. Die Überladungsauflösung schlägt zur Laufzeit fehl, da d1 den Laufzeittyp int aufweist und exampleMethod2 eine Zeichenfolge erfordert.
// Valid.
ec.exampleMethod2("a string");
// The following statement does not cause a compiler error, even though ec is not
// dynamic. A run-time exception is raised because the run-time type of d1 is int.
ec.exampleMethod2(d1);
// The following statement does cause a compiler error.
//ec.exampleMethod2(7);

Dynamic Language Runtime
Die Dynamic Language Runtime (DLR) ist eine neue API in .NET Framework 4. Diese stellt die Infrastruktur bereit, die den dynamic-Typ in C# sowie die Implementierung von dynamischen Programmiersprachen wie IronPython und IronRuby unterstützt. Weitere Informationen zur DLR finden Sie unter Übersicht über die Dynamic Language Runtime.

COM-Interop
Visual C# 2010 bietet mehrere Funktionen zur Verbesserung der Interoperation mit COM-APIs, wie beispielsweise Office-Automatisierungs-APIs. Dazu zählen der dynamic-Typ sowie benannte und optionale Argumente. Viele COM-Methoden ermöglichen die Variation von Argumenttypen und Rückgabetyp durch Festlegen der Typen als object. Dies erforderte zur Koordination mit stark typisierten Variablen in C# die explizite Umwandlung der Werte. Wenn Sie mit der /link (C#-Compileroptionen)-Option kompilieren, ermöglicht Ihnen der neue dynamic-Typ, die object-Vorkommen in COM-Signaturen wie Elemente vom Typ dynamic zu behandeln, sodass ein Großteil der Umwandlung nicht mehr erforderlich ist. Anhand der folgenden Beispielanweisungen können Sie den Zugriff auf eine Zelle in einem Microsoft Office Excel-Arbeitsblatt mit dem dynamic-Typ und ohne den dynamic-Typ vergleichen.
// Before the introduction of dynamic.
((Excel.Range)excelApp.Cells[1, 1]).Value2 = "Name";
Excel.Range range2008 = (Excel.Range)excelApp.Cells[1, 1];
// After the introduction of dynamic, the access to the Value property and
// the conversion to Excel.Range are handled by the run-time COM binder.
excelApp.Cells[1, 1].Value = "Name";
Excel.Range range2010 = excelApp.Cells[1, 1];

Verwandte Themen
|