当我打电话时WrapperAsync AsyncLocalContext.Value返回空值。当我在方法外运行相同的代码块时,在Main方法中,AsyncLocalContext.Value不为空(这是我所期望的)。
功能完全相同,但结果不同。这是Asynclocal班级的错误还是有其他解释?
internal class Program
{
private static readonly AsyncLocal<string> AsyncLocalContext = new AsyncLocal<string>();
private static void Main()
{
const string text = "surprise!";
WrapperAsync(text).Wait();
Console.WriteLine("Get is null: " + (AsyncLocalContext.Value == null));
// AsyncLocalContext.Value is null
var value = GetValueAsync(text).Result;
AsyncLocalContext.Value = value;
Console.WriteLine("Get is null: " + (AsyncLocalContext.Value == null));
// AsyncLocalContext.Value is not null
Console.Read();
}
private static async Task WrapperAsync(string text)
{
var value = await GetValueAsync(text); …Run Code Online (Sandbox Code Playgroud) 我想传递一个IEnumerable<T>枚举值(枚举具有 Flags 属性)并返回聚合值。下面的方法有效,但前提是枚举使用默认Int32类型。如果它使用byte或Int64它将不起作用。
public static T ToCombined<T>(this IEnumerable<T> list) where T : struct
{
if (!typeof(T).IsEnum)
throw new ArgumentException("The generic type parameter must be an Enum.");
var values = list.Select(v => Convert.ToInt32(v));
var result = values.Aggregate((current, next) => current | next);
return (T)(object)result;
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以获得基础类型:
Type enumType = typeof(T);
Type underlyingType = Enum.GetUnderlyingType(enumType);
Run Code Online (Sandbox Code Playgroud)
但我不知道如何在方法中使用它。我如何制作扩展方法,以便它可以处理enums具有 flags 属性的任何列表?
更好,但可能是非常大的 UInts 的问题
public static T ToCombined<T>(this IEnumerable<T> list) where T : struct
{ …Run Code Online (Sandbox Code Playgroud)