Why does the type inference in C# not work with dynamic objects and generic methods?

↘锁芯ラ 提交于 2019-12-25 15:03:22

问题


I am working on a project that uses C# generics in combination with the dynamic keyword to implement a simple prototxt Caffe file parser, which is based on the proto2 syntax from the Google protocol buffer project.

The parser uses a very simple grammar to read in a prototxt file and store the values in a dictionary of type Dictionary<string, dynamic>.

The dynamic objects are used to enable very flexible access to the values and to enable nesting of types, such as Dictionary<string, Dictionary<string, dynamic>> during the parsing process and a generic method is used for type casting to enable autocompletion and reaasure type safety.

See the following scenario:

// prototxt file
layer {
  name: "conv2/norm2"
  …
  lrn_param {
    local_size: 5
    …
  }
}

// method in C#
public T Try<T>(dynamic dict, string key, T @default = default(T)) {
  var result = @default;
  try {
    result = (T)dict[key];
  } catch {} // do nothing
  return result;
}
…

// usage
var learnParamDict = Try<Dictionary<string, dynamic>>(layer, “lrn_param”);

Now to my problem:

When using the above code, the compiler does not really get that the return type of the method is typed to Dictionary<string, dynamic> and shows dynamic only, but when pointing with the cursor to the Try method Visual Studio (the compiler) does describe the right types: see image - part 1

I have experimented further and found out that you can completely ignore the Generic declaration and the static type definition, but this of course results to a Runtime Error: see image - part 2

Now to my questions:

What is the correct behavior of the dynamic type inference, when working with generics? / Why is the type inference with dynamic objects and generics somehow unclear?

Shouldn't the compiler at least detect that I cannot use var with a generic method without declaring a type?

Meta Info:

I am using C# 6 with the Target framework setting for .NET Framework 4.6.2 and working with Visual Studio 2017 Version 15.1 (26403.7) Release.

来源:https://stackoverflow.com/questions/44006718/why-does-the-type-inference-in-c-sharp-not-work-with-dynamic-objects-and-generic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!