开发者

Implement linq's Cast<T>() on single objects

How would you implement the Cast<T>() method of linq on single objects?

Here's the scenario:

public interface IFoo
{
    String Message { get; set; }
}

public class Foo : IFoo
{
    IFoo.Message { get; set; }
    internal SecretMessage { get; set; } // secrets are internal to the assembly
}

internal class Fubar
{
    public IFoo Foo { get; set; }
}

I'd like to be able to do...

fubarInstance.Foo.Cast<Foo>.SecretMessage = "";
开发者_如何学JAVA

Instead of...

((Foo)fubarInstance.Foo).SecretMessage = "";


Why? Why not use the casting syntax which is familiar to every C# programmer on the planet? Unless you can think of very definite benefits to performing the cast in a method, stick to the built-in mechanism.

If you really want to, you could write:

public static T Cast<T>(this object o) {
    return (T) o;
}

... but I would strongly recommend you not to do it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜