How can I get close to non-nullable reference types in C# today?

守給你的承諾、 提交于 2019-12-17 19:09:41

问题


I've read many of the non-nullable questions and answers. It looks like the best way to get close to non-nullable types in C# (4.0) is Jon Skeet's NonNullable<> hack.

However, it seems that C++/CLI has solved much of the problem by supporting managed references: Foo% (instead of native C++ Foo&). The compiler makes this work by adding modreq(IsImplicitlyDereferenced) to the argument. Trying to call such a function from C# results in:

'<FunctionName>' is not supported by the language

Is there anything better then NonNullable<>?

Is there any way to (reasonably--i.e., w/o using reflection) call a C++/CLI method Foo::Method(Bar%) from C#?


[edit] It seems there is currently nothing better than NonNullable<>...I wish I would have gotten some comments on the C++/CLI stuff as it already has at least a partial solution.


回答1:


I've run into this a few times...I've yet to find anything better than Skeet's solution. It's solved all the cases I've come across, so I have to give it my vote.

I agree it's a bit of a hacky situation that we have to resort to that...but his fix does solve the problem.




回答2:


Yep, spec#: http://research.microsoft.com/en-us/projects/specsharp/

-- Edit: I just noticed you said C# 4.0; I'm fairly sure Spec# doesn't support that version. Nevertheless, it's worth a review.

You may also be able (I think) to check at a slightly later stage then compile, via a rule in Gendarme: http://www.mono-project.com/Gendarme (assuming that runs against 4.0)



来源:https://stackoverflow.com/questions/2181846/how-can-i-get-close-to-non-nullable-reference-types-in-c-sharp-today

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