Specifically we're making our application compatible with the Out Of Process Session State server where all types saved 开发者_JS百科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;
}
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.
You could write a custom FxCop rule to generate warnings for this scenario.
Jason Block has a sample rule on his site.
精彩评论