How do you limit the general method to classes with the specified attribute?

I want to create a general method that applies only to classes with an attribute Serializable, for example.

public static int Foo<T>(T obj) where T : Serializable {
  ...
}

but obviously the above does not compile. And I suppose that if I put there SerializableAttribute, he will insist on what Tis an attribute, not a class with that attribute.

How do you do something like this?

+3
source share
3 answers

Attribute restrictions cannot be met. One solution might be to use reflection to analyze the object passed to your method and see if it has a declared attribute Serializable.

+4

ISerializable " T: ISerializable", ISerializable . SerializableAttribute , . , , , , . - ...

public interface ISerializableSet {
    bool IsSerializable { get; }
}

, , Foo " T: ISerializableSet" .

...

public interface ISerializableSet
{
    bool IsSerializable { get; }
}

[Serializable]
class SerializableClass : ISerializableSet
{
    [NonSerialized]
    private bool _runTimeCheck = true;

    #region ISerializableSet Members
    public bool IsSerializable
    {
        get { 
            if(!_runTimeCheck)
                return true;
            if(0 != (this.GetType().Attributes & System.Reflection.TypeAttributes.Serializable))
                return true;
            return false;
        }
    }
    #endregion
}

public static class Bar2
{
    public static int Foo<T>(T obj) where T : ISerializableSet
    {
        ISerializableSet sc = obj;
        Console.WriteLine("{0}", sc.IsSerializable.ToString());
        return 1;
    }
}

IsSerializable , - [Serializable] . Unit Tests, .

+2

You must force these classes to implement an interface that uses this attribute. Then you can filter by interface:

public static int Foo<T>(T obj) where T : ISerializable
{}
0
source

Source: https://habr.com/ru/post/1768237/


All Articles