Vin*_*ent 2 c# intellisense dynamic visual-studio
说我有以下方法:
private void something()
{
string text = "This is obviously a string";
dynamic pietje = Guid.NewGuid();
var dict = new Dictionary<Guid, string>();
dict.Add(pietje, text);
var someText = dict[pietje];
}
Run Code Online (Sandbox Code Playgroud)
下面的图片显示IntelliSense仍然认为它是动态的,即使我没有看到这可能是一个字符串以外的任何东西(或null)

我错过了一个设置还是有什么东西阻止IntelliSense知道someText应该是一个字符串?我可能会过度依赖IntelliSense,但某些对象很难正确地手动输入整个方法或属性名称.
那是什么原因呢?我有什么办法可以解决这个问题吗?
很明显我可以通过多种方式修复它:
string someText = dict[pietje];
var someText = dict[(Guid)pietje];
var someText = dict[pietje] as string;
Run Code Online (Sandbox Code Playgroud)
但这不是重点,也不是我想要的.
在许多情况下,这个问题都会出现.SO中的经典问题:
public string Foo(string fooable) { .... }
dynamic fooable = "whatever";
var whyAmIDynamic = Foo(fooable);
Run Code Online (Sandbox Code Playgroud)
咦?为什么wyAmIDynamic dynamic?!?编译器应该知道wyAmIDynamic的string,不应该吗?
是的,但随后其他人出现并写下以下内容:
public int Foo(int fooable) { .... } //a new overload of Foo
Run Code Online (Sandbox Code Playgroud)
现在,应该Foo(fooable)回归什么?dynamic似乎是唯一合理的选择; 涉及dynamic参数的方法调用直到运行时才能解析.
在您的特定情况下,编译器没有理由不相信有人可能会出现并执行以下荒谬的重载Dictionary<TKey, TValue>:
public int this[string key] { ... }
Run Code Online (Sandbox Code Playgroud)
这种过载是否有意义?是否编译器业务是否有意义?不,这合法吗?是的,因此索引器返回一个dynamic变量.
| 归档时间: |
|
| 查看次数: |
97 次 |
| 最近记录: |