小编Hyr*_*lex的帖子

委派行动:新行动还是演员行动?

我发现了使用Action初始化Delegate的两种不同方法:

创建新操作或强制转换为Action.

Delegate foo = new Action(() => DoNothing(param));
Delegate bar = (Action)(() => DoNothing(param));
Run Code Online (Sandbox Code Playgroud)

这两种语法有区别吗?

哪一个更好,为什么?

委托用于此示例,因为语法对于使用lambda表达式调用BeginInvoke或Invoke等方法很有用,将lambda表达式强制转换为动作非常重要

static main 
{
    Invoke((Action)(() => DoNothing())); // OK
    Invoke(new Action(() => DoNothing())); // OK
    Invoke(() => DoNothing()); // Doesn't compil
}

private static void Invoke(Delegate del) { }
Run Code Online (Sandbox Code Playgroud)

但有趣的是看到编译器授权:

Action action = () => DoNothing();
Invoke(action);
Run Code Online (Sandbox Code Playgroud)

c# lambda delegates action casting

14
推荐指数
1
解决办法
1万
查看次数

在单元测试输出目录中添加内容文件

我是visual studio中的单元测试的新手,我想加载一个物理xml文件.此文件作为内容在单元测试项目中,并在输出目录中复制.

因此,当我编译项目时,xml文件位于输出目录中.但是当我执行测试时,会创建一个包含所有相关DLL的新目录,但不会复制xml文件.

执行测试需要Xml的内容.我执行此代码以检索执行文件夹中的Xml文件的路径:

private static string GetXmlFullName()
{
    // GetApplicationPath use the current DLL to find the physical path
    // of the current application
    string executeDirectory = AssemblyHelper.GetApplicationPath();
    return Path.Combine(executeDirectory, "content.xml");
}
Run Code Online (Sandbox Code Playgroud)

例外是:

System.IO.DirectoryNotFoundException: 'd:\***\solutiondirectory\testresults\*** 2012-06-13 17_59_53\out\content.xml'.
Run Code Online (Sandbox Code Playgroud)

如何在execute文件夹中添加此文件?

提前致谢.(对不起我的英文...)

c# unit-testing visual-studio

8
推荐指数
1
解决办法
6950
查看次数

标签 统计

c# ×2

action ×1

casting ×1

delegates ×1

lambda ×1

unit-testing ×1

visual-studio ×1