Reputation: 3979
I have a class which is using generics. This class do some operation which need serialization. So the class which will be given to myClass must hold the attribute [Serializable()]. Is it possible to request a class which attributes it holds? In best case at design time.
[Serializable()]
public class clsSchnappschuss<T>
{
//Some operations which need serialization
}
So if someone uses clsSchnappschuss he must give the DataType (T) and i want to request that T implements [Serializable()]. Is this possible?
regards
Upvotes: 1
Views: 147
Reputation: 727027
You cannot request a presence of an attribute statically (i.e. at compile time), but inside the code your generic type you can examine T
as if it were an actual type name. For example, you can request its typeof
, and pull attributes from it:
public class clsSchnappschuss<T> {
static clsSchnappschuss() {
if (Attribute.GetCustomAttribute(typeof(T), typeof(SerializableAttribute)) == null) {
throw new InvalidOperationException(typeof(T).FullName +" is not serializable.");
}
}
}
Note that I put the check in a static constructor. This would execute once before any other code that uses clsSchnappschuss<>
for each particular type.
Upvotes: 4
Reputation: 111
if your given classes implement the ISerializeable interface you could to following:
public class clsSchnappschuss<T> where T : ISerializable
Upvotes: 0