1 Star 1 Fork 0

defa/aspnetcore_study

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
IFeatureCollection.cs 3.40 KB
一键复制 编辑 原始数据 按行查看 历史
defa 提交于 2018-02-05 14:40 +08:00 . miniHost Serverʵ
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Demo
{
public interface IFeatureCollection : IEnumerable<KeyValuePair<Type, object>>
{
bool IsReadOnly { get; }
int Revision { get; }
object this[Type key] { get; set; }
TFeature Get<TFeature>();
void Set<TFeature>(TFeature instance);
}
public class FeatureCollection : IFeatureCollection
{
private static KeyComparer FeatureKeyComparer = new KeyComparer();
private readonly IFeatureCollection _defaults;
private IDictionary<Type, object> _features;
private volatile int _containerRevision;
public FeatureCollection()
{
}
public FeatureCollection(IFeatureCollection defaults)
{
_defaults = defaults;
}
public virtual int Revision
{
get { return _containerRevision + (_defaults?.Revision ?? 0); }
}
public bool IsReadOnly { get { return false; } }
public object this[Type key]
{
get
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
object result;
return _features != null && _features.TryGetValue(key, out result) ? result : _defaults?[key];
}
set
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (value == null)
{
if (_features != null && _features.Remove(key))
{
_containerRevision++;
}
return;
}
if (_features == null)
{
_features = new Dictionary<Type, object>();
}
_features[key] = value;
_containerRevision++;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<KeyValuePair<Type, object>> GetEnumerator()
{
if (_features != null)
{
foreach (var pair in _features)
{
yield return pair;
}
}
if (_defaults != null)
{
// Don't return features masked by the wrapper.
foreach (var pair in _features == null ? _defaults : _defaults.Except(_features, FeatureKeyComparer))
{
yield return pair;
}
}
}
public TFeature Get<TFeature>()
{
return (TFeature)this[typeof(TFeature)];
}
public void Set<TFeature>(TFeature instance)
{
this[typeof(TFeature)] = instance;
}
private class KeyComparer : IEqualityComparer<KeyValuePair<Type, object>>
{
public bool Equals(KeyValuePair<Type, object> x, KeyValuePair<Type, object> y)
{
return x.Key.Equals(y.Key);
}
public int GetHashCode(KeyValuePair<Type, object> obj)
{
return obj.Key.GetHashCode();
}
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C#
1
https://gitee.com/defa/aspnetcore_study.git
git@gitee.com:defa/aspnetcore_study.git
defa
aspnetcore_study
aspnetcore_study
master

搜索帮助