gpt4 book ai didi

c# - 如何获取在 C# 中作为参数传递的表达式的字符串表示形式?

转载 作者:行者123 更新时间:2023-11-30 23:02:43 25 4
gpt4 key购买 nike

我有一个用于检查参数的静态方法...

require(myStringVariable);

如果该值不满足某些要求,我只想显示一条消息。

是否可以同时显示作为参数传递的变量(或表达式)的名称? (在 C++ 中,带有 stringize 运算符的宏可以完成这项工作。在 C# 中是否有任何等效或其他工具可以完成同样的工作?)

更新:我没有搜索任何类似nameof(myStringVariable) 的东西。实际上,我也想调用该方法:

require(bareFname + ".ext");

如果表达式无法通过检查,那么我会在方法中做类似的事情

static void required(... theExpressionArgument)
{
string value = evaluate theExpressionArgument;
if (value.Length == 0)
{
Console.WriteLine("ERROR: Non empty value is required for the expression "
+ theExpressionArgument);
}
}

最佳答案

基于 this answer ,您可以像这样重写您的方法:

public static void RequireNotEmpty(Expression<Func<string>> lambda)
{
// Get the passed strings value:
string value = lambda.Compile().Invoke();

// Run the check(s) on the value here:
if (value.Length == 0)
{
// Get the name of the passed string:
string parameterName = ((MemberExpression) lambda.Body).Member.Name;

Console.WriteLine($"ERROR: Non empty value is required for the expression '{parameterName}'.");
}
}

然后可以这样调用:

string emptyString = "";
RequireNotEmpty(() => emptyString);

ERROR: Non empty value is required for the expression 'emptyString'.


请注意,上面的代码假定您只想检查字符串。如果不是这种情况,您可以使用签名 public static void RequireNotEmpty<T>(Expression<Func<T>> lambda)这将适用于任何类型 T .

我还将该方法重命名为我认为更易读且更有意义的名称。


编辑:推荐

阅读您的评论后,我认为这可能是您想要的:

public static class Checker
{
private static T GetValue<T>(Expression<Func<T>> lambda)
{
return lambda.Compile().Invoke();
}

private static string GetParameterName<T>(Expression<Func<T>> lambda)
{
return ((MemberExpression) lambda.Body).Member.Name;
}

private static void OnViolation(string message)
{
// Throw an exception, write to a log or the console etc...
Console.WriteLine(message);
}

// Here come the "check"'s and "require"'s as specified in the guideline documents, e.g.

public static void RequireNotEmpty(Expression<Func<string>> lambda)
{
if(GetValue(lambda).Length == 0)
{
OnViolation($"Non empty value is required for '{GetParameterName(lambda)}'.");
}
}

public static void RequireNotNull<T>(Expression<Func<T>> lambda) where T : class
{
if(GetValue(lambda) == null)
{
OnViolation($"Non null value is required for '{GetParameterName(lambda)}'.");
}
}

...
}

现在您可以利用 Checker像这样上课:

public string DoStuff(Foo fooObj, string bar)
{
Checker.RequireNotNull(() => fooObj);
Checker.RequireNotEmpty(() => bar);

// Now that you checked the preconditions, continue with the actual logic.
...
}

现在,当您调用 DoStuff参数无效,例如

DoStuff(new Foo(), "");

消息

Non empty value is required for 'bar'.

写入控制台。

关于c# - 如何获取在 C# 中作为参数传递的表达式的字符串表示形式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50337945/

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