我试图允许用户提供自定义数据并使用自定义类型管理数据。用户的算法会将时间同步的事件推送到他们定义的事件处理程序中。
我不确定这是否可能,但这是我想构建的“概念证明”代码。它没有在 for 循环中检测到 T:“找不到类型或命名空间名称 'T'”
class Program
{
static void Main(string[] args)
{
Algorithm algo = new Algorithm();
Dictionary<Type, string[]> userDataSources = new Dictionary<Type, string[]>();
// "User" adding custom type and data source for algorithm to consume
userDataSources.Add(typeof(Weather), new string[] { "temperature data1", "temperature data2" });
for (int i = 0; i < 2; i++)
{
foreach (Type T in userDataSources.Keys)
{
string line = userDataSources[typeof(T)][i]; //Iterate over CSV data..
var userObj = new T(line);
algo.OnData < typeof(T) > (userObj);
}
}
}
//User's algorithm pattern.
interface IAlgorithm<TData> where TData : class
{
void OnData<TData>(TData data);
}
//User's algorithm.
class Algorithm : IAlgorithm<Weather> {
//Handle Custom User Data
public void OnData<Weather>(Weather data)
{
Console.WriteLine(data.date.ToString());
Console.ReadKey();
}
}
//Example "user" custom type.
public class Weather {
public DateTime date = new DateTime();
public double temperature = 0;
public Weather(string line) {
Console.WriteLine("Initializing weather object with: " + line);
date = DateTime.Now;
temperature = -1;
}
}
}
编辑:
string line = userDataSources[t][i]; //Iterate over CSV data..
var userObj = Activator.CreateInstance(t);
algo.OnData<t>(userObj);
同样的错误,但现在它在 OnData 上,所以它不能调用泛型事件,因为它不将 T 识别为泛型类型?