简体   繁体   English

如何在StringTemplate中的对象上调用C#扩展方法?

[英]How can I call a C# extension method on an object in StringTemplate?

I'm trying to do an if...then in StringTemplate based on the number of items in a collection. 我正在尝试基于集合中项目的数量在StringTemplate中执行if ... then ... I want to do this: 我想做这个:

$if(length(myCollection) > 1)$ $ if(长度(myCollection)> 1)$

But, this is considered logic, and is therefore forbidden (StringTemplate doesn't recognize the > operator). 但是,这被认为是逻辑,因此被禁止(StringTemplate无法识别>运算符)。

But, will StringTemplate reflect out an extension method? 但是,StringTemplate会反映出扩展方法吗?

My extension method looks like this: 我的扩展方法如下:

public static bool IsMoreThanOne(this ICollection list)
{
    return list.Count > 1;
}

If my template looks like this: 如果我的模板如下所示:

$if(myCollection.MoreThanOne)$

That would find the method if it were a "first order" method (meaning on the "myCollection" object). 如果它是“一阶”方法(在“ myCollection”对象上表示),则将找到该方法。 But it's not -- it's an extension method, so it doesn't seem to be working. 但这不是-它是一种扩展方法,因此似乎无效。

For this particular logic you can use the following expression, which basically says "if we skip the first item, does the remaining collection contain any items?": 对于此特定逻辑,您可以使用以下表达式,该表达式基本上表示:“如果我们跳过第一个项目,则剩余集合中是否包含任何项目?”:

$if(rest(myCollection))$

In general, you can create an implementation of IModelAdaptor which supports accessing specific properties of your object. 通常,您可以创建IModelAdaptor的实现,该实现支持访问对象的特定属性。 If your implementation extends ObjectModelAdaptor or MapModelAdaptor , you can fall back to return base.GetProperty(...) for any properties that you don't handle yourself. 如果您的实现扩展了ObjectModelAdaptorMapModelAdaptor ,那么您可以退回以return base.GetProperty(...)来获取任何您自己无法处理的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM