假設我有以下代碼。代表泛型類型未知的泛型操作。如何創建類似的東西?
static class Store<T> {
public static T A;
public static T B;
public static T C;
}
public static class Store {
public static Value A = new Value(<T>(v) => Store<T>.A = v); //just an example of what I want
public static Value B = new Value(<T>(v) => Store<T>.B = v); //just an example of what I want
public static Value C = new Value(SetC<T>); //just an example of what I want
public static void SetA<T>(T value) { Store<T>.A = value; }
public static void SetB<T>(T value) { Store<T>.B = value; }
public static void SetC<T>(T value) { Store<T>.C = value; }
}
public class Value {
Action<T><T> _valueChanger; //just an example of what I want
public Value(Action<T><T> valueChanger) { //just an example of what I want
_valueChanger = valueChanger;
}
public void SetValue<T> (T value) {
_valueChanger<T>(value); //just an example of what I want
}
}
我想寫Store.A.SetValue(42)
以便值保存到Store<int>.A
。我可以寫什麼,而不是以「僅僅是我想要的例子」爲標記的行來實現? (我想探索不涉及字典或類似的解決方案)
改寫的問題: 我想修改類Value
(定義某些字段,寫一個構造函數和編寫方法Value.SetValue( t值)),則構造類型值的三個不同的變量(A,B,C)以這樣的方式,當我打電話Store.A.SetValue(42)
值Store<int>.A
被改變爲42
類的另一種變化:
static class Holder<T> {
T Value { get; set; }
}
static class Store2<T> {
public static Holder<T> A = new Holder<T>();
public static Holder<T> B = new Holder<T>();
public static Holder<T> C = new Holder<T>();
}
public static class Store2 {
public static Value A = new Value2(Store2<>.A); //just an example of what I want
public static Value B = new Value2(Store2<>.B); //passing non-specific generic expression
public static Value C = new Value3({TFree}() => Store2<TFree>.C); //just an example of what I want
}
public class Value2 { //Non-generic class!
Holder{TFree}<TFree> _holder; //just an example of what I want
public Value(Holder{TFree}<TFree> holder) { //just an example of what I want
_holder = holder;
}
public void SetValue<T> (T value) {
_holder{T}.Value = value; //just an example of what I want
}
}
public class Value3 { //Non-generic class! (Another variation)
Func{TFree}<Holder<TFree>> _holderFactory; //just an example of what I want
public Value(Func{TFree}<Holder<TFree>> holderFactory) { //just an example of what I want
_holderFactory = holderFactory;
}
public void SetValue<T> (T value) {
Holder<T> holder = _holderFactory{T}(); //just an example of what I want
holder.Value = value;
}
}
解決方案: 一個簡單的反射和無收集的解決方案是使用回答另一個問題(Emulating delegates with free generic type parameters in C#和Emulating delegates with free generic type parameters in C#)發現。解決方案是Delegates to generic operations where the generic type is unknown. How to create something like that?。
你能改說這個問題嗎?我沒有得到你想要做的。 – GregRos
改寫了這個問題。 –