今天晚上我一直在玩自定义属性,看看我是否可以简化我的缓存层。我想出了以下几点:
namespace AttributeCreationTest
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false)]
public class Cache : Attribute
{
public Cache()
{
Length = "01h:30m";
}
public string Length;
}
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class CacheIdentifier : Attribute
{
}
[Cache]
class Class1
{
[CacheIdentifier]
public int ID { get; set; }
}
class Class2
{
[CacheIdentifier]
public bool ID { get; set; }
}
[Cache(Length = "01h:10m")]
class Class3
{
[CacheIdentifier]
public string ID { get; set; }
}
class Program
{
static void Main(string[] args)
{
var f1 = new Class1 { ID = 2 };
var f2 = new Class2 { ID = false };
var f3 = new Class3 { ID = "someID" };
DoCache(f1);
DoCache(f2);
DoCache(f3);
}
public static void DoCache(object objectToCache)
{
var t = objectToCache.GetType();
var attr = Attribute.GetCustomAttribute(t, typeof(Cache));
if (attr == null) return;
var a = (Cache)attr;
TimeSpan span;
if (TimeSpan.TryParse(a.Length.Replace("m", "").Replace("h", ""), out span))
{
Console.WriteLine("name: {0}, {1}", t.Name, span);
ExtractCacheData(objectToCache);
return;
}
throw new Exception(string.Format("The Length value of {0} for the class {1} is invalid.", a.Length, t.Name));
}
public static void ExtractCacheData(object o)
{
var t = o.GetType();
foreach (var prop in t.GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
if (Attribute.IsDefined(prop, typeof(CacheIdentifier)))
{
Console.WriteLine(" type: {0}, value {1}", prop.PropertyType, prop.GetValue(o));
break;
}
throw new Exception(string.Format("A CacheIdentifier attribute has not been defined for {0}.", t.Name));
}
}
}
}
“缓存”属性将被充实,但我在学习 C# 的这一领域时将其保持在最低限度。我的想法是允许更轻松地缓存项目,包括指定缓存对象的时间量的简化方法。
这看起来好吗?使用这种模式将项目推送到缓存是否会对性能产生重大影响?
我还没有找到任何详细介绍这种想法的教程,所以任何建议都将不胜感激。