Linq
Aggregate 聚合
字符串替换
//study<Aggregate>first => study-Aggregate-first
var invalidFileName = Path.GetInvalidFileNameChars();
var replaceResult = invalidFileName.Aggregate("study<Aggregate>first", (accmulate, result) => (accmulate.Replace(result, '-')));
Console.WriteLine(replaceResult);
累加求和 1 - 100
var list = Enumerable.Range(1,100);
var result = list.Aggregate((a,b)=>(a+b));
Console.WriteLine(string.Format("1 - 100 sum {0}",result));
Tips: 对于累加可以使用等差数列求和的方式.(end-start+1)*(end + start)/2
eg:
return serviceFactory
.GetInstances<IPipelineBehavior<TRequest, TResponse>>()
.Reverse()
.Aggregate((RequestHandlerDelegate<TResponse>) Handler, (next, pipeline) => () => pipeline.Handle((TRequest)request, cancellationToken, next))();
Assembly
yield 参考 C#图解教程 356 page
Assembly.DefinedTypes 返回值为IEnumerable<Type>
要实现IEnumerable即实现 current MoveNext Reset 复杂类型实现起来会很繁琐
class Program
{
static void Main(string[] args)
{
HelloCollection helloCollection = new HelloCollection();
foreach (string s in helloCollection)
{
Console.WriteLine(s);
}
Console.ReadKey();
}
}
//public class HelloCollection : IEnumerable
//{
// public IEnumerator GetEnumerator()
// {
// yield return "Hello";
// yield return "World";
// }
//}
public class HelloCollection : IEnumerable
{
public IEnumerator GetEnumerator()
{
Enumerator enumerator = new Enumerator(0);
return enumerator;
}
public class Enumerator : IEnumerator, IDisposable
{
private int state;
private object current;
public Enumerator(int state)
{
this.state = state;
}
public bool MoveNext()
{
switch (state)
{
case 0:
current = "Hello";
state = 1;
return true;
case 1:
current = "World";
state = 2;
return true;
case 2:
break;
}
return false;
}
public void Reset()
{
throw new NotSupportedException();
}
public object Current
{
get { return current; }
}
public void Dispose()
{
}
}
}
}
只访问ARRAY的前8个数据,做如下修改.yield break跳出迭代
public IEnumerator GetEnumerator()
{
for (int i = 0; i < 10; i++)
{
if (i < 8)
{
yield return array[i];
}
else
{
yield break;
}
}
}
Reflection
TryAddTransient 根据ServiceType进行判断,已存在的服务不再添加
AddTransient 每个服务都将创建不同的实例
IsGenericType 是否是泛型
IsGenericTypeDefinition 是否可以用于泛型构建
ContainsGenericParameters 是否是开放性泛型 无法为开放性泛型构建新实例
GetGenericTypeDefinition() 获取相关泛型类型(开放类型)
IsAssignableFrom :typeof(Animal).IsAssignableFrom(typeof(Dog)) is True explain Dog implementation Animal