C# 如何向OnChangeEventHandler添加参数
我需要为插入到数据库中的不同“符号”行设置不同的SqlDependencies 如何在OnChangeEventHandler设置中传递符号C# 如何向OnChangeEventHandler添加参数,c#,sql-server,event-handling,sqldependency,C#,Sql Server,Event Handling,Sqldependency,我需要为插入到数据库中的不同“符号”行设置不同的SqlDependencies 如何在OnChangeEventHandler设置中传递符号 public void SetDepedencyForSymbol(string symbol) { string cmdText = "SELECT [Symbol] FROM [" + AccountCode + "].[FilledOrders] WHERE [Symbol] = '" + symbol + "'"; using (S
public void SetDepedencyForSymbol(string symbol)
{
string cmdText = "SELECT [Symbol] FROM [" + AccountCode + "].[FilledOrders] WHERE [Symbol] = '" + symbol + "'";
using (SqlCommand command = new SqlCommand(cmdText, conn))
{
SqlDependency FilledDependency = new SqlDependency(command);
FilledDependency.OnChange += new OnChangeEventHandler(OnDependencyForFillsChange);
using (SqlDataReader reader = command.ExecuteReader())
{
// Process the DataReader.
}
}
}
void OnDependencyForFillsChange(object sender, SqlNotificationEventArgs e)
{
// Handle the event (for example, invalidate this cache entry).
// How can I get value of "symbol" here
}
不能更改事件处理程序的签名。
SqlDependency
的OnChange
事件的处理程序将始终接受对象
和SqlNotificationEventArgs
,并且您无法更改它
不过,您可以使用匿名委托来处理事件。然后您将能够访问symbol参数:
public void SetDepedencyForSymbol(string symbol)
{
string cmdText = "SELECT [Symbol] FROM [" + AccountCode + "].[FilledOrders] WHERE [Symbol] = '" + symbol + "'";
OnChangeEventHandler handler = (sender, args) =>
{
string theSymbol = symbol;
// Handle the event (for example, invalidate this cache entry).
};
using (SqlCommand command = new SqlCommand(cmdText, conn))
{
SqlDependency FilledDependency = new SqlDependency(command);
FilledDependency.OnChange += handler;
using (SqlDataReader reader = command.ExecuteReader())
{
// Process the DataReader.
}
}
}
您迫切需要阅读、理解并开始使用参数化查询。这段代码对sql注入非常开放。至于手头的问题,我不明白你想做什么。您有一些代码只是漂浮在空间中,但其余部分在一个方法中。@SeanLange我编辑了这个问题以将其放入一个方法中。我想知道当我到达OnDependencyForFillsChange时,哪个“符号”被用来设置依赖项,这正是我想要的。