限制在C#中使用匿名类型

时间:2012-11-21 14:39:29

标签: c# asp.net-mvc anonymous-types

我想搜索以下所有地方,例如Controllers中的匿名类型使用如下。

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

在上述情况下,returnDataJsonResult,我们在Razor次观看中使用它来解析AJAX次请求的状态。

我希望在这种情况下尽量减少匿名类型的使用,因为这可能是维护问题,因为如果任何行写为new { Succes = true, Message = "Operation completed successfully"},编译器不会引发任何警告/错误,并且它将导致运行 - 客户端脚本中的时间错误。

任何有关限制此类情况或检测此类情况的见解都将受到赞赏。

3 个答案:

答案 0 :(得分:4)

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

\bnew\s*{

答案 1 :(得分:2)

只是不要使用匿名类型。使用您计划使用的数据创建新的具体类型:

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

然后这些行可以改为:

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

答案 2 :(得分:0)

如何包装json调用以便运行时错误/断言:

首先是从这里检测匿名的扩展程序: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;
    }
}

然后将它用作新方法。

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

现在,您可以轻松搜索非法直接拨打JsonConvert.SerializeObject的地方。