Is it possible to have a compile time check that a type is marked with the Serializable attribute

跟風遠走 提交于 2019-12-12 07:24:50

问题


Specifically we're making our application compatible with the Out Of Process Session State server where all types saved in session must be serializable.

Is there a way to see at compile time that any type put into HttpSessionState is marked with the Serializable attribute. Something along the lines of this 'non-valid' code

public static void Put<T>( string key, T value ) where T : IsMarkedWitheSerializableAttribute
{
   HttpContext.Current.Session[key] = value;
}

回答1:


You could write a custom FxCop rule to generate warnings for this scenario.

Jason Block has a sample rule on his site.




回答2:


No, there's no kind of generic constraint like that. Attributes are generally meant to indicate something about the implementation of a type. You'll have to either introduce your own marker interface (urgh) or insert an execution-time check and hope that your testing is sufficient.

Eric Lippert's post about properties and attributes is good to read here. It's not quite the same question, as it's talking more about objects vs types, but it's still relevant in terms of attributes expressing mechanics.



来源:https://stackoverflow.com/questions/4803172/is-it-possible-to-have-a-compile-time-check-that-a-type-is-marked-with-the-seria

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