vdh*_*ant 5 .net performance static-methods fluent-interface instance-methods
我正在为我正在玩的一些简单的验证内容创建一些流畅的界面.我注意到的一件事是我创建了很多不同的对象.
例如,鉴于以下陈述:
Check.Assertion.ForValue.That(value, "value").IsNotNull() : void
Check.Assertion.ForArgument.That(value, "value").IsNotNull() : void
Validate.Assertion.ForDate.That("Test").IsNotNull() : bool
Validate.Assertion.ForNumeric.That("Test").IsNotNull() : bool
Run Code Online (Sandbox Code Playgroud)
每个'.' (接受最后一个)我正在新建一个对象.如果我在这里没有使用流畅的界面,我会使用静态方法.
我想知道的是,如果有人知道在使用这些实例对象(注意它们是非常小的对象)时会注意到性能上的任何真正差异,就像使用静态方法一样.
干杯安东尼
请注意,您不一定需要在整个地方构建新对象.您可以通过接口解决大部分流畅的接口,并在一个对象上实现大量接口.在这种情况下,您this只需通过新界面即可返回.
例:
public interface ICheckAssertionForValue
{
ICheckAssertionForValueThat That(Object value, String name);
}
public interface ICheckAssertion
{
ICheckAssertionForValue ForValue { get; }
}
public class Check : ICheckAssertion
{
public static ICheckAssertion Assertion
{
get { return new Check(); }
}
ICheckAssertionForValue ICheckAssertion.ForValue
{
get { return this; } // <-- no new object here
}
ICheckAssertionForValueThat ICheckAssertionForValue.That(Object value, String name)
{
return new SomeOtherObject(value, name);
}
}
Run Code Online (Sandbox Code Playgroud)