使构造函数仅接受 C# 中具有 [Serializable] 属性的对象

Make constructor to only accept objects with [Serializable] attribute in C#

我希望我的构造函数只接受具有 [Serializable] 属性的对象。

public MyClass(object obj)
{
}

类似于:

public MyClass(? obj)
{
}

我如何在 C# 中做到这一点

我想到的第一件事是通过只允许实现 ISerializable 接口的对象来简化它:

public MyClass(ISerializable obj)
{
    // ...
}

但我觉得太简单了,不是吗?

或者:

public MyClass(Object obj)
{
    if (!Attribute.IsDefined(obj.GetType(), typeof(SerializableAttribute)))
        throw new ArgumentException("The object must have the Serializable attribute.","obj");

    // ...
}

我认为您甚至可以使用以下方法检查它:

obj.GetType().IsSerializable;