Dynamic.md 1.1 KB
Newer Older
F
feilong 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
# dynamic 类型

下面的代码在编译时时错误的:

```csharp
// 编译错误,object和int不能相加
object n = 10;
int result = n + 5;
Console.WriteLine("result:{0}", result);
```

而下面的代码可以在编译时通过,运行时正常执行:

```csharp
// 编译时不检查类型,运行时才检查
dynamic n = 10;
int result = n + 5;
Console.WriteLine("result:{0}", result);
```

dynamic 的用途就是在编译时忽略类型检查,延迟到运行期再检查。现在有下面的代码

```csharp
class Test{
    public static dynamic Double(dynamic d){
        if (d is int){
            return d*2;
        }else if(d is string){
            return d+d;
        }else{
            throw new Exception("Not support");
        }
    }
}
```

以下关于 上述 dynamic 的代码调用,运行时会出错的是?

## 答案

```csharp
Console.WriteLine(Test.Double(new object()));
```

## 选项


### A
```csharp
Console.WriteLine(Test.Double(10));
```

### B
```csharp
Console.WriteLine(Test.Double("10"));
```

### C
```csharp
Console.WriteLine(Test.Double(10/2));
```