我已经痛苦地意识到需要在事件驱动的GUI代码中编写以下代码模式的频率,其中
private void DoGUISwitch() {
// cruisin for a bruisin' through exception city
object1.Visible = true;
object2.Visible = false;
}
Run Code Online (Sandbox Code Playgroud)
变为:
private void DoGUISwitch() {
if (object1.InvokeRequired) {
object1.Invoke(new MethodInvoker(() => { DoGUISwitch(); }));
} else {
object1.Visible = true;
object2.Visible = false;
}
}
Run Code Online (Sandbox Code Playgroud)
这是C#中的一个尴尬模式,无论是记忆还是打字.有没有人提出某种捷径或构造,在一定程度上自动化?如果有一种方法可以将函数附加到执行此检查的对象,而不必经历所有这些额外的工作,如object1.InvokeIfNecessary.visible = true类型快捷方式,那就太酷了.
上一页答案已经讨论的只是打电话的invoke()每次不切实际,甚则调用()语法既效率低下,仍然尴尬应对.
那么,有没有人想出任何捷径?
我试图从一个线程读取一个combobox.Text而不是它创建的线程,但我收到错误:
System.Windows.Forms.dll中发生了未处理的"System.InvalidOperationException"类型异常
附加信息:跨线程操作无效:控制'levelsComboBox'从其创建的线程以外的线程访问.
我之前使用过.Invoke但只是设置属性,我怎么用它来读取combobox.Text?因为.Invoke返回void,我需要一个字符串.或者没有Invoke有另一种方法吗?
我希望我能恰当地提出问题的标题.
在c#中,我可以使用lambdas(作为委托),或者使用较旧的委托语法来执行此操作:
Func<string> fnHello = () => "hello";
Console.WriteLine(fnHello());
Func<string> fnHello2 = delegate()
{
return "hello 2";
};
Console.WriteLine(fnHello2());
Run Code Online (Sandbox Code Playgroud)
那么为什么我不能"内联"lambda或委托体,并避免在命名变量中捕获它(使其匿名)?
// Inline anonymous lambda not allowed
Console.WriteLine(
(() => "hello inline lambda")()
);
// Inline anonymous delegate not allowed
Console.WriteLine(
(delegate() { return "hello inline delegate"; })()
);
Run Code Online (Sandbox Code Playgroud)
在javascript中工作的示例(仅用于比较)是:
alert(
(function(){ return "hello inline anonymous function from javascript"; })()
);
Run Code Online (Sandbox Code Playgroud)
这会产生预期的警报框.
更新:看起来你可以在C#中使用内联匿名lambda,如果你适当地进行转换,但是()的数量开始让它变得难以驾驭.
// Inline anonymous lambda with appropriate cast IS allowed
Console.WriteLine(
((Func<string>)(() => "hello inline anonymous …Run Code Online (Sandbox Code Playgroud) 我有一些重载方法的问题,我会尝试给它一个简单的实现.
所以这里有一个类包含以下两种方法:
public class MyRepo<TEntity>
{
public List<TEntity> GetData(Expression<Func<TEntity, Boolean>> expression)
{
//Do something
}
public List<TEntity> GetData(Func<TEntity,Boolean> whereClause)
{
//Do something
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的实体:
public class MyEntity
{
public int Id { get; set; }
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这是我正在使用它的地方:
{
...
MyRepo<MyEntity> myRepo = new MyRepo<MyEntity>();
myRepo.GetData(x => x.Id == 1); // The ambiguity point
...
}
Run Code Online (Sandbox Code Playgroud)
问题是我只有两个具有相同名称和不同参数的方法,因此,基于OOP多态性概念,我希望.NET能够理解我想要的方法.
但很明显.NET 无法理解,因为实例形式Expression<Func<TEntity, Boolean>>和Func<TEntity, Boolean>是相同的,这里面.NET引发编译时错误:
The call is ambiguous between the following …Run Code Online (Sandbox Code Playgroud) 所以我在C#中有以下代码:
public Container ConfigureSimpleInjector(IAppBuilder app)
{
var container = new Container();
container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
container.RegisterPackages();
app.Use(async (context, next) =>
{
using (AsyncScopedLifestyle.BeginScope(container))
{
await next();
}
});
container.Verify();
return container;
}
Run Code Online (Sandbox Code Playgroud)
在app.Use()被定义为Owin.AppBuilderUserExtensions.Use(),看起来像这样:
public static IAppBuilder Use(this IAppBuilder app, Func<IOwinContext, Func<Task>, Task> handler);
VB等价如下:
Public Function ConfigureSimpleInjector(app As IAppBuilder) As Container
Dim container = New Container()
container.Options.DefaultScopedLifestyle = New AsyncScopedLifestyle()
container.RegisterPackages()
app.Use(Async Sub(context, [next])
Using AsyncScopedLifestyle.BeginScope(container)
Await [next]()
End Using
End Sub)
container.Verify()
Return container
End …Run Code Online (Sandbox Code Playgroud) 我有一个方法,我想转换为扩展方法
public static string GetMemberName<T>(Expression<Func<T>> item)
{
return ((MemberExpression)item.Body).Member.Name;
}
Run Code Online (Sandbox Code Playgroud)
并称之为
string str = myclass.GetMemberName(() => new Foo().Bar);
Run Code Online (Sandbox Code Playgroud)
所以评估为 str = "Bar"; // It gives the Member name and not its value
现在,当我尝试将此转换为扩展方法时
public static string GetMemberName<T>(this Expression<Func<T>> item)
{
return ((MemberExpression)item.Body).Member.Name;
}
Run Code Online (Sandbox Code Playgroud)
并称之为
string str = (() => new Foo().Bar).GetMemberName();
Run Code Online (Sandbox Code Playgroud)
错误说 Operator '.' cannot be applied to operand of type 'lambda expression'
我哪里错了?
我发生的是从上一次按钮点击动态创建的列表视图.然后ti启动一个后台工作程序,其中应该清除listview并每30秒用新信息填充iistview.
我不断得到:跨线程操作无效:控制'listView2'从一个线程访问,而不是创建它的线程.
private void watcherprocess1Updatelist()
{
listView2.Items.Clear();
string betaFilePath1 = @"C:\Alpha\watch1\watch1config.txt";
using (FileStream fs = new FileStream(betaFilePath1, FileMode.Open))
using (StreamReader rdr = new StreamReader((fs)))
{
while (!rdr.EndOfStream)
{
string[] betaFileLine = rdr.ReadLine().Split(',');
using (WebClient webClient = new WebClient())
{
string urlstatelevel = betaFileLine[0];
string html = webClient.DownloadString(urlstatelevel);
File.AppendAllText(@"C:\Alpha\watch1\specificconfig.txt", html);
}
}
}
Run Code Online (Sandbox Code Playgroud)