简体   繁体   中英

C# Interface with static property or methods?

I need to define a static property or method in certain classes of my bussiness logic, to explicity determine which classes are cacheables in Session or Cache of ASP.NET service. I'm thinking, static property or method in the interface would be perfect, but C# 4.0 doesn't support this.

All a need is be able to evaluate in a generic manager which classes are cacheables and, if they are, at what level: session (user) or cache (application).

Now I'm trying with a empty interface with T parameter to evaluate, but, maybe exists a better approach?? Thanks.

public interface ICacheable<T>
{
}

public class Country : ICacheable<CacheApplication>
{
}

public class Department : ICacheable<CacheUser>
{
}

public class Gestor<T>
{
    // ...
    if (typeof(T) is ICacheable<CacheApplication>)
    {
    }
    // ...
}

How about using a custom attribute? Your classes then would look something like this:

[Cacheable(Level = CacheLevels.Application)]
public class Country { }

[Cacheable(Level = CacheLevels.User)]
public class Department { }

You can read here on how to create your own custom attribute and then access its value by using reflection.

You cant define static interfaces, for one thing, you cant make instances of static classes so you cant substitute them for others with the same base class.

You might be better off having a singleton instance of one class and using interfaces as normal. You could enforce one and one-only instance through a factory pattern too.

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