开发者

Wicked JUnit Date trick - How would you do this in C#?

Gojko Adzic posted today on his blog about Steve Freeman's unit-testing trick, which helped make it crystal clear why the date comparison in the unit test failed. Here is the blog post describing the trick - it is not long.

The key part of the trick is this method (in Java), which overrides ToString() on a particular instance of the Date class.

private Date n开发者_如何学PythonamedDate(final String name, final Date date) {
    return new Date(date.getTime()){
        @Override
        public String toString() {
            return name;
        }
    };
}

It appears that this method uses a facility of Java language that doesn't have a match in C# (or at least one that I know of). If you could show me how to do the same trick in C#, that would be awesome.


That is called an anonymous class in Java. It is really just a class implementation with no name, that overrides ToString()

You would be able to the same in C# with a normal, named class - the only problem being, that DateTime is a struct in C#, so you cannot inherit from it.

C# does have anonymous types, but not in the same way as Java. In C# you can have an anonymous type and specify it's properties, but you cannot specify any method implementations. Therefore, anonymous types in C# and Java tends to be used for different things.

Edit

Here is an example on how you would do it in C#, but as stated above, you cannot do it on DateTime (or other structs, or sealed classes) in C#. So for the sake of the example; I am using an imaginary class called Token, that has a single string property "Value":

private Token GetNamedToken(Token t, string name)
{
    return new NamedToken {Value = t.Value, Name = name};
}

private class NamedToken : Token
{
    public string Name { get; set; }
    public override string ToString()
    {
        return Name;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜