[英]Modifying Expression<Func<object>>
I need to modify a given Expression.我需要修改给定的表达式。
The default Expression will be called like this:默认表达式将被调用如下:
LocalizationService.Current.GetString(() => GeneralResources.Products)
Where GeneralResources.Products is a static string:其中GeneralResources.Products是 static 字符串:
public class GeneralResources
{
public static string Products => "Products";
public static string ProductsExtra => "Products extra";
}
Now I've added a method to check on a specific something to change the Expression so not GeneralResources.Products will be used but GeneralResources.ProductsExtra现在我添加了一个方法来检查特定的东西来改变表达式,所以不会使用GeneralResources.Products而是使用GeneralResources.ProductsExtra
But I don't know how to exactly change this object.但我不知道如何准确更改这个 object。
This is what I've so far:这是我到目前为止:
public static string GetString(
this LocalizationService service,
Expression<Func<object>> resource,
params object[] formatArguments)
{
if (customCheck == true)
{
// TODO: Change from GeneralResources.Products (resource) to GeneralResources.ProductsExtra
var translation = service.GetStringByCulture(() => resource + "Extra", CultureInfo.CurrentUICulture, formatArguments);
if (!string.IsNullOrEmpty(translation)) return translation;
}
return service.GetStringByCulture(resource, CultureInfo.CurrentUICulture, formatArguments);
}
Hopefully someone can help me out.希望有人可以帮助我。
Thanks in advance!提前致谢!
Grtz Sander格茨桑德
Finally fixed it with this code:最后用这段代码修复它:
public static string GetString(
this LocalizationService service,
Expression<Func<object>> resource,
params object[] formatArguments)
{
if (resource == null)
throw new ArgumentNullException(nameof(resource));
if (customCheck == true)
{
try
{
var body = resource.Body as MemberExpression;
MemberExpression member = Expression.Property(null, body.GetDeclaringType(), body.Member.Name + "Extra");
resource = Expression.Lambda<Func<object>>(member);
var translation = service.GetStringByCulture(resource, CultureInfo.CurrentUICulture, formatArguments);
if (!string.IsNullOrEmpty(translation)) return translation;
}
catch
{
//ignore exception, means that translation isn't available
}
}
return service.GetStringByCulture(resource, CultureInfo.CurrentUICulture, formatArguments);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.