且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么是铸造类对象的动态对象抛出空引用异常?

更新时间:2023-01-17 16:08:30

我同意与其他回答者谁说,这看起来像一个错误。特别是,它似乎是在C#运行时绑定层中的错误,虽然我还没有彻底调查它。

我的错误道歉。我会把它报告给C#5测试团队,我们将看看它是否已经被报告并固定在C#5(它再现了最近的测试版,所以这是不可能的,它已经被报道和固定。 )如果不是这样,一个解决方法是不可能把它做成了最终版本。在这种情况下,我们会考虑的一个可能的服务版本。

感谢您将这一引起我们的注意。如果你觉得进入了一个连接问题跟踪它,随意这样做,请包括一个链接到这个计算器的问题。如果你不这样做,没有问题;测试团队将知道它无论哪种方式。

I have the following function:

public static T TryGetArrayValue<T>(object[] array_, int index_)
{
    ... //some checking goes up here not relevant to question

    dynamic boxed = array_[index_];
    return (T)boxed;
}

When I call it in the following way,

object a = new object();
object v = TUtils.TryGetArrayValue<object>(new object[] { a }, 0);

(T)boxed throws a null reference exception.

Any other type I put in there other than "object", it works perfectly fine.
Any ideas what this is, and why it's throwing the exception?

Edit: The reason why I use dynamic is to avoid exception when converting types, for example:

double a = 123;
int v = TUtils.TryGetArrayValue<int>(new object[] { a }, 0);

I agree with the other answerers who say that this looks like a bug. Specifically it appears to be a bug in C# runtime binding layer, though I have not investigated it thoroughly.

I apologize for the error. I'll report it to the C# 5 testing team and we'll see if it has already been reported and fixed in C# 5. (It reproduces in the recent beta release, so it is unlikely that it has already been reported and fixed.) If not, a fix is unlikely to make it into the final release. In that case we'll consider it for a possible servicing release.

Thanks for bringing this to our attention. If you feel like entering a Connect issue to track it, feel free to do so and please include a link to this *** question. If you don't, no problem; the test team will know about it either way.