【问题标题】:C# - passing SomeClass to a function instead of typeof(SomeClass)C# - 将 SomeClass 传递给函数而不是 typeof(SomeClass)
【发布时间】:2013-02-18 09:47:40
【问题描述】:

我已经实现了一个ActionFilterAttribute,它将SomeClass 映射到SomeOtherClass。这是构造函数:

public class MapToAttribute : ActionFilterAttribute
{
    private Type _typeFrom;
    private Type _typeTo;
    public int Position { get; set; }

    public MapToAttribute(Type typeFrom, Type typeTo, int Position = 0)
    {
        this.Position = Position;
        this._typeFrom = typeFrom;
        this._typeTo = typeTo;
    }

    ...
}

目前的调用方式是:

MapTo(typeof(List<Customer>), typeof(List<CustomerMapper>), 999)

出于审美原因,我更愿意这样做

MapTo(List<Customer>, List<CustomerMapper>, 999)

我试过了

    public MapToAttribute(object typeFrom, object typeTo, int Position = 0)
    {
        this.Position = Position;
        this._typeFrom = typeof(typeFrom);
        this._typeTo = typeof(typeTo);
    }

但无济于事,因为 Visual Studio 会假装 typeFromtypeTo 未定义。


编辑:Attributes 不支持泛型的使用(否则显然是正确的,如下所述)。

【问题讨论】:

    标签: c# constructor typeof


    【解决方案1】:

    您不能将类型用作变量。一般来说,你可以使用泛型来摆脱typeof

    public class MapToAttribute<TFrom, TTo> : ActionFilterAttribute
    {
        private Type _typeFrom;
        private Type _typeTo;
        public int Position { get; set; }
    
        public MapToAttribute(int Position = 0)
        {
            this.Position = Position;
            this._typeFrom = typeof(TFrom);
            this._typeTo = typeof(TTo);
        }
    
        ...
    }
    

    用法:

    new MapToAttribute<List<Customer>, List<CustomerMapper>>(999);
    

    问题:
    C# 不允许通用属性,因此您只能使用 typeof
    没有其他办法。

    【讨论】:

    • 嘿丹尼尔。感谢您的迅速答复。我不确定是否可以在Filter 属性中使用泛型。现在就试试。
    • 更新:Attributes 中不能使用泛型。无赖。
    • @vzwick:真可惜。我相应地更新了我的答案。你被typeof困住了。
    【解决方案2】:

    你不能那样做。除非使用泛型或 typeof,否则类型不能作为参数传递。 Daniel Hilgarth 的解决方案很棒,但如果您的类打算用作属性,因为 c# 不允许通用属性,则该解决方案将不起作用。

    【讨论】:

      猜你喜欢
      • 2021-10-01
      • 2018-12-13
      • 2011-05-27
      • 2020-06-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-01
      • 2014-12-27
      • 1970-01-01
      相关资源
      最近更新 更多