开发者

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

开发者 https://www.devze.com 2023-01-15 16:38 出处:网络
How would you implement the Cast<T>() method of linq on single objects? Here\'s the scenario: public interface IFoo

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

精彩评论

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