c# – 可覆盖的方法不能是静态的:我怎样才能做我想做的事情?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 可覆盖的方法不能是静态的:我怎样才能做我想做的事情?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含4929字,纯文字阅读大概需要8分钟。
内容图文
![c# – 可覆盖的方法不能是静态的:我怎样才能做我想做的事情?](/upload/InfoBanner/zyjiaocheng/779/ecf3eddcbf9b4c64835b99b2b294c610.jpg)
我有一系列静态类,用于获取枚举值的字符串.他们都看起来像这样:
public static class MyEnumToString
{
private static Dictionary<MyEnum, string> map
= new Dictionary<MyEnum, string>();
public static string Get(MyEnum type)
{
PopulateEmptyMap();
return map[type];
}
static void PopulateEmptyMap()
{
if (!map.Any())
{
PopulateMap();
}
}
private static void PopulateMap()
{
map[MyEnum.enum1] = "string for enum 1";
map[MyEnum.enum2] = "string for enum 2";
}
}
我有这样的多个类,它们使用的Enum类型和字符串值不同.显然,我应该结合使用这些类来减少重复的代码.
我尝试做的是创建通用基类,以便它可以处理任何类型,然后为继承的类实现PopulateMap.如果有可能,它看起来像这样:
public static class TypeToString<TType>
{
public static Dictionary<TType, string> map
= new Dictionary<TType, string>();
public static string Get(TType type)
{
PopulateEmptyMap();
return map[type];
}
static void PopulateEmptyMap()
{
if (!map.Any())
{
PopulateMap();
}
}
public abstract static void PopulateMap();
}
public static class MyEnumToString: TypeToString<MyEnum>
{
public static void PopulateMap()
{
map[MyEnum.enum1] = "string for enum 1";
map[MyEnum.enum2] = "string for enum 2";
}
}
我不得不将字典和方法PopulateMap公开,因为显然泛型类不能有protected或protected-internal成员.必须公开这个并不理想,但不是一个交易破坏者.
我所依赖的是“可覆盖的方法不能是静态的”,所以我的PopulateMap方法既不能是抽象的,也不能是静态的.如果它不是静态的,则无法从其他静态方法调用它.如果它不是抽象的,那么继承类的PopulateMap就不会被调用.
这个版本甚至没有构建.
有没有办法做我想做的事情,仍然保持我的班级静态?每次我想调用TypeToString.Get()时,我真的想避免必须有一个实例化的TypeToString对象.
解决方法:
这是一个方便的扩展方法,因为我猜你正在尝试将一些描述文本映射到枚举值:
public static class EnumExtensions
{
public static string GetDescription(this Enum value)
{
var field = value.GetType().GetField(value.ToString());
if (field == null)
return value.ToString();
var attribute = field.GetCustomAttributes(typeof(DescriptionAttribute), false)
.OfType<DescriptionAttribute>()
.SingleOrDefault();
return attribute != null
? attribute.Description
: value.ToString();
}
}
像这样使用它:
public enum Foo
{
[Description("Hello")]
Bar,
[Description("World")]
Baz
}
var value = Foo.Bar;
var description = value.GetDescription(); // Hello
根据您的需要,如果反射被证明对您来说太慢,您可以缓存描述,只需修改GetDescription方法即可.
编辑:考虑评论中的其他信息.
由于看起来您需要更具可扩展性的东西,您可以使用自定义属性:
[AttributeUsage(AttributeTargets.Field, AllowMultiple = true, Inherited = false)]
public sealed class DescriptionEntryAttribute : Attribute
{
public string Key { get; private set; }
public string Value { get; private set; }
public DescriptionEntryAttribute(string key, string value)
{
Key = key;
Value = value;
}
}
哪个可以让你这样做:
public enum Foo
{
[DescriptionEntry("Name", "Hello")]
[DescriptionEntry("Title", "Some title")]
Bar,
[DescriptionEntry("Name", "World")]
[DescriptionEntry("Title", "Some title")]
Baz
}
现在,要阅读此内容,我建议您将其存储在这样的缓存中:
public static class EnumExtensions
{
private static readonly ConcurrentDictionary<Type, DescriptionCache> Caches = new ConcurrentDictionary<Type, DescriptionCache>();
public static string GetDescription(this Enum value, string key)
{
var enumType = value.GetType();
var cache = Caches.GetOrAdd(enumType, type => new DescriptionCache(type));
return cache.GetDescription(value, key);
}
public static IEnumerable<TEnum> GetValuesFromDescription<TEnum>(string key, string description)
where TEnum : struct
{
var cache = Caches.GetOrAdd(typeof(TEnum), type => new DescriptionCache(type));
return cache.GetValues(key, description).Select(value => (TEnum)(object)value);
}
private class DescriptionCache
{
private readonly ILookup<Enum, Tuple<string, string>> _items;
private readonly ILookup<Tuple<string, string>, Enum> _reverse;
public DescriptionCache(Type enumType)
{
if (!enumType.IsEnum)
throw new ArgumentException("Not an enum");
_items = (from value in Enum.GetValues(enumType).Cast<Enum>()
let field = enumType.GetField(value.ToString())
where field != null
from attribute in field.GetCustomAttributes(typeof (DescriptionEntryAttribute), false).OfType<DescriptionEntryAttribute>()
select new {value, key = attribute.Key, description = attribute.Value})
.ToLookup(i => i.value, i => Tuple.Create(i.key, i.description));
_reverse = (from grp in _items
from description in grp
select new {value = grp.Key, description})
.ToLookup(i => i.description, i => i.value);
}
public string GetDescription(Enum value, string key)
{
var tuple = _items[value].FirstOrDefault(i => i.Item1 == key);
return tuple != null ? tuple.Item2 : null;
}
public IEnumerable<Enum> GetValues(string key, string description)
{
return _reverse[Tuple.Create(key, description)];
}
}
}
这条路:
> Foo.Bar.GetDescription(“Name”)返回“Hello”
> EnumExtensions.GetValuesFromDescription< Foo>(“Title”,“Some title”)返回包含Foo.Bar和Foo.Baz的序列
这应该足以让你开始,现在你应该调整它以满足你的需求.例如,您可以使用枚举而不是字符串作为键,这有助于避免键入错误,但我不知道这是否适合您的需要.
内容总结
以上是互联网集市为您收集整理的c# – 可覆盖的方法不能是静态的:我怎样才能做我想做的事情?全部内容,希望文章能够帮你解决c# – 可覆盖的方法不能是静态的:我怎样才能做我想做的事情?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。