C#: Globally alias a generic class name?

前端 未结 2 973
星月不相逢
星月不相逢 2021-01-14 11:43

in some project we are using Generics, and we get a lot of lines like this:

Line myLine =
           (Line

        
2条回答
  •  猫巷女王i
    2021-01-14 12:35

    No such thing as a global alias. What you can do is use type inference to simplify your declarations:

    var myLine = (Line)LineFactory.CreateLine(...);
    

    and if that's not specific enough for the inference system, you can make the CreateLine() method generic to enforce it:

    var myLine = LineFactory.CreateLine>(...);
    

    and given the name of the LineFactory type, maybe even simplify it some more:

    var myLine = LineFactory.CreateLine(...);
    

    This last option feels "right" to me in some way I can't fully articulate. Just in case you need a little help, the method declaration would look like something this:

    public static class LineFactory 
    {
        public static Line CreateLine(...) { ... }
    }
    

提交回复
热议问题