简体   繁体   中英

Restricting usage of Anonymous Type in C#

I'd like to search all the places like following where the Anonymous types in Controllers is being used as follows.

if(success) {
    returnData = JsonConvert.SerializeObject(new { Success = true, Message = "Operation completed successfully" });
}
else {
    returnData = JsonConvert.SerializeObject(new { Success = false, Message = "Operation failed" });
}

In above case the returnData is a JsonResult and its used in our Razor views to parse the status of the AJAX requests.

I want to minimize the usage of Anonymous types in such case as this could be maintenance issue as compiler would not raise any warning/errors if any of the line is written as new { Succes = true, Message = "Operation completed successfully"} and it would result into run-time error in the client-side scripts.

Any insights on restricting such situation or detecting such instances would be appreciated.

为什么不在解决方案/项目中使用“使用正则表达式”选项进行搜索?

\bnew\s*{

Just don't use an anonymous type. Create a new concrete type with the data you plan to use:

public class JSONMessage
{
    public string Message { get; set; }
    public bool Success { get; set; }
}

Then those lines can be changed to:

if(success) {
    returnData = JsonConvert.SerializeObject(new JSONMessage(){ Success = true, Message = "Operation completed successfully" });
}
else {
    returnData = JsonConvert.SerializeObject(new JSONMessage(){ Success = false, Message = "Operation failed" });
}

How about wrapping up the json call so you can have run time error/assert:

First an extension to detect anonymous from here: Determining whether a Type is an Anonymous Type

public static class TypeExtension {

    public static Boolean IsAnonymousType(this Type type) {
        var hasCompilerGeneratedAttribute = type.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false).Count() > 0;
        var nameContainsAnonymousType = type.FullName.Contains("AnonymousType");
        var isAnonymousType = hasCompilerGeneratedAttribute && nameContainsAnonymousType;    
        return isAnonymousType;
    }
}

Then use that it your new method.

 public static object JsonSeralize(object obj)
   {
      Debug.Assert(!obj.getType().IsAnonymousType());     
      return JsonConvert.SerializeObject(obj);
   }

Now you can easily search for places that illegally call JsonConvert.SerializeObject directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM