简体   繁体   中英

How can I make a Linq extension for objects with a specific attribute?

I'm interested in making a extension for objects that have an attribute (in this case [ProtoContract] ).

For example, the extension would work on:

[ProtoContract]
class myClass{
     //stuff
}

... but not on ...

class someRandomClass
{
}

The difference here is that usually you can make a extension function like this:

public static byte[] Serialize<T>(this T instance){

... but in this case I want it to only work on classes with the [ProtoContract] attribute.

Is this possible?

It is possible to make a runtime check with reflection inside youre Serialize method, but not to make the check compile time since attributes are not part of the type's signature.

If you want to have compile time checking you would have to use a (slightly ugly) interface with no methods instead of an attribute.

You won't be able to filter that with the where , you'll just have to throw an exception. Consider this:

public static byte[] Serialize<T>(this T instance)
{
    if (!Attribute.IsDefined(typeof(T), typeof(ProtoContractAttribute)))
    {
        throw new Exception(...);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM