我有以下代碼,它根據作為引數傳遞的值的型別存盤要執行的操作串列...
Action<int> intAction = x => Console.WriteLine($"You sent an int: {x}");
Action<bool> boolAction = x => Console.WriteLine($"You sent a bool: {x}");
var funcsByInputType = new Dictionary<Type, Action<object>>();
funcsByInputType[typeof(int)] = (object x) => intAction((int)x);
funcsByInputType[typeof(bool)] = (object x) => boolAction((bool)x);
PerformAction(true);
PerformAction(42);
void PerformAction<TValue>(TValue value)
{
if (funcsByInputType!.TryGetValue(typeof(TValue), out Action<object>? action))
{
action(value!);
}
}
這按預期作業。
我現在想做的是從一個我只呼叫一次的方法創建字典,所以我可以像這樣重寫我的代碼。
Action<int> intAction = x => Console.WriteLine($"You sent an int: {x}");
Action<bool> boolAction = x => Console.WriteLine($"You sent a bool: {x}");
funcsByInputType = MakeFuncsByInputType(intAction, boolAction);
PerformAction(true);
PerformAction(42);
void PerformAction<TValue>(TValue value)
{
if (funcsByInputType!.TryGetValue(typeof(TValue), out Action<object>? action))
{
action(value!);
}
}
我怎么能寫MakeFuncsByInputType方法?
請注意,我不想多次呼叫該方法,也不想將我的引數定義為params object[]
uj5u.com熱心網友回復:
這是不可能的,因為通過 anAction<object>作為別名Action<string>I 將能夠傳遞42而不是字串。
所以我不得不改用構建器模式。
public static partial class Reducer { public static Builder New() => new Builder();
public class Builder<TState>
{
private bool Built;
private ImmutableArray<KeyValuePair<Type, Func<TState, object, Result<TState>>>> TypesAndReducers;
internal Builder() => TypesAndReducers = ImmutableArray.Create<KeyValuePair<Type, Func<TState, object, Result<TState>>>>();
public Builder<TState> Add<TDelta>(Func<TState, TDelta, Result<TState>> reducer)
{
if (reducer is null)
throw new ArgumentNullException(nameof(reducer));
EnsureNotBuilt();
TypesAndReducers = TypesAndReducers.Add(new(typeof(TDelta), (state, delta) => reducer(state, (TDelta)delta)));
return this;
}
public Func<TState, object, Result<TState>> Build()
{
EnsureNotBuilt();
if (TypesAndReducers.Length == 0)
throw new InvalidOperationException("Must add at least one reducer to build.");
Built = true;
var dictionary = TypesAndReducers
.GroupBy(x => x.Key)
.ToDictionary(x => x.Key, x => x.Select(x => x.Value));
return (TState state, object delta) =>
{
if (delta is null)
throw new ArgumentNullException(nameof(delta));
if (!dictionary.TryGetValue(delta.GetType(), out var reducers))
return (false, state);
bool anyChanged = false;
TState newState = state;
foreach(var reducer in reducers)
{
(bool changed, newState) = reducer(newState, delta);
anyChanged |= changed;
}
return anyChanged
? (true, newState)
: (false, state);
};
}
private void EnsureNotBuilt()
{
if (Built)
throw new InvalidOperationException("Reducer has already been built.");
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/460202.html
上一篇:快速泛型:未找到陣列的追加
