gpt4 book ai didi

c# - 使用 StoryQ 修改或配置输出

转载 作者:行者123 更新时间:2023-11-28 20:24:23 26 4
gpt4 key购买 nike

我在 StoryQ discussion boards 上发布了这个问题,但通过查看对其他问题的(缺乏)回答,那里的事件充其量似乎很少。我想我应该让这里的每个人都试一试。

有没有办法修改或配置输出(输出窗口和文件)以包含自定义字符串?例如,我的一个故事要求抛出一个特定的异常。为此,我捕获异常并保存它,然后在一个单独的方法中测试它是否为非空且属于所需类型。我希望能够将异常类型附加到输出(很像参数附加到方法调用)。

例如

.Then(ExceptionIsThrown<ArgumentNullException>)

将导致以下输出

then exception is thrown (ArgumentNullException)

最佳答案

感谢Giorgio Minardi指导我研究 StoryQ.Formatting 命名空间。在那里我发现我可以使用一个简单的属性来覆盖方法格式化。

该 API 提供了一个 OverrideMethodFormatAttribute(从抽象类 MethodFormatAttribute 继承而来),如果您想使用特定的字符串常量,它可以工作,但 C# 不喜欢属性中方法的类型参数。由于属性中的 T 而无法编译:

[OverrideMethodFormat(string.Format("exception is thrown ({0})", typeof(T).Name))]
private void ExceptionIsThrown<T>() where T : Exception
{
...
}

解决方案是创建另一个 MethodFormatAttribute 子类,专门搜索泛型类型的方法并输出它们。这个子类如下:

public class GenericMethodFormatAttribute : MethodFormatAttribute
{
private readonly string _textFormat;

public GenericMethodFormatAttribute()
{
_textFormat = null;
}

public GenericMethodFormatAttribute(string textFormat)
{
_textFormat = textFormat;
}

public override string Format(MethodInfo method,
IEnumerable<string> parameters)
{
var generics = method.GetGenericArguments();
if (_textFormat == null)
{
var genericsList = string.Join<Type>(", ", generics);
return string.Format("{0} ({1})",
UnCamel(method.Name),
genericsList);
}
return string.Format(_textFormat, generics);
}
}

用法几乎类似于提供的属性,只是您可以选择提供格式字符串而不是字符串常量。省略格式字符串 un-camel-cases 方法名称就像默认行为一样。

[GenericMethodFormatAttribute]
private void ExceptionIsThrown<T>() where T : Exception
{
...
}

这让我可以在我的源代码中声明属性,而不必触及 StoryQ 代码。十点 StoryQ 的可扩展性!

关于c# - 使用 StoryQ 修改或配置输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15226666/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com