【问题标题】:C# extension method to objects with specific attribute具有特定属性的对象的 C# 扩展方法
【发布时间】:2012-04-13 07:38:31
【问题描述】:

我创建了一个扩展方法,它会告诉我我创建的每个对象的大小 像这样:

public static int CalculateKilobytes(this object notSuspectingCandidate)
{
    using (MemoryStream stream = new MemoryStream())
    {
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Serialize(stream, notSuspectingCandidate);
        return stream.ToArray().Count() / 1000;
    }
}

由于我使用的是serializaion,并非所有对象都能够返回答案,只有可序列化的对象。有没有办法将此方法附加到可以序列化的对象上?

【问题讨论】:

    标签: serialization extension-methods


    【解决方案1】:

    你可以使用Type.IsSerializable Property

    public static int CalculateKilobytes(this object notSuspectingCandidate)
        {          
                using (MemoryStream stream = new MemoryStream())
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    if (notSuspectingCandidate.GetType().IsSerializable) {
                        formatter.Serialize(stream, notSuspectingCandidate);
                        return stream.ToArray().Count() / 1000;
                    }
                    return 0;
                }         
        }
    

    【讨论】:

    • 嗨,感谢您的快速响应,我有几种方法可以防止异常(也可以使用 try/catch)。我希望防止扩展方法出现在编译时不可序列化的对象中
    【解决方案2】:

    如果您打算稍后再次序列化它,那么序列化一个对象只是为了获取它的大小是一种非常糟糕的做法。

    谨慎使用。

    扩展方法将应用于所有对象,您必须检查它是否具有自定义属性。

    这项检查可以完成这项工作。

    if (notSuspectingCandidate.GetType().GetCustomAttributes(typeof(SerializableAttribute), true).Length == 0)
    {
        return -1; // An error
    }
    

    另一种方法是将扩展方法放入 ISerializable 并在所有需要的类型中使用该接口。

    public static int CalculateKilobytes(this ISerializable notSuspectingCandidate)
    {
        using (MemoryStream stream = new MemoryStream())
        {
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(stream, notSuspectingCandidate);
            return stream.ToArray().Count() / 1000;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-09
      • 1970-01-01
      • 1970-01-01
      • 2016-08-11
      • 2013-08-09
      • 2022-01-13
      • 2020-11-21
      相关资源
      最近更新 更多