简体   繁体   English

在C#中,为什么使用动态类型允许我在泛型上使用运算符?

[英]In C#, why does using dynamic type allow me to use operators on generics?

In class we have being dealing with generics and were asked to complete an assignment. 在课堂上,我们正在处理泛型,并被要求完成一项任务。

We created an Account<T> class with one property private T _balance; 我们创建了一个Account<T>类,其中一个属性为private T _balance; and then had to write methods to credit and debit _balance . 然后不得不写信贷和借记_balance

Credit method (partial) called from Main by eg acc1.Credit(4.6); 通过例如acc1.Credit(4.6);从Main调用的Credit method (partial acc1.Credit(4.6); :

    public void Credit(T credit)
    {
        Object creditObject = credit;
        Object balanceObject = _balance;

        Type creditType = creditObject.GetType();
        Type balanceType = balanceObject.GetType();

        if(creditType.Equals(balanceType))
        {
            if(creditType.Equals(typeof (double)))
            {
                 balanceObject= (double)balanceObject + (double)creditObject;
            }
       ...WITH more else if's on int,float and decimal.
        }
        _balance = (T)balanceObject;   
    }

I had to condition check and cast as I cannot _balance += (T)balanceObject; 我不得不条件检查和施放,因为我不能_balance += (T)balanceObject; as this will give the error "Operator '+' cannot be applied to operand of type 'T'" 因为这会给错误"Operator '+' cannot be applied to operand of type 'T'"

During my reading on the subject I discovered the dynamic type. 在我阅读这个主题的过程中,我发现了dynamic类型。 In my new Account class I added a new method and changed the Credit method to: (called from Main by eg acc1.Credit(4.6); ) 在我的新Account类中,我添加了一个新方法并将Credit方法更改为:(从Main调用例如acc1.Credit(4.6);

    public void Credit(dynamic credit)
    {
        _balance += ConvertType(credit);
    }
    public T ConvertType(object input)
    {
        return (T)Convert.ChangeType(input, typeof(T));
    }

This is what I don't understand. 这是我不明白的。 The credit method takes in the object as type dynamic and the ConvertType(object input) returns it as type T . credit方法将对象作为dynamic类型, ConvertType(object input)将其作为类型T返回。 Why does using dynamic type allow me to use operators on generics? 为什么使用动态类型允许我在泛型上使用运算符?

When using dynamic types, resolution is deferred until runtime. 使用dynamic类型时,分辨率将延迟到运行时。 If, at runtime, the generic type supports a + operator, your code will work. 如果在运行时,泛型类型支持+运算符,则代码将起作用。 If not, it will throw an exception. 如果没有,它将抛出异常。

From a MSDN article on dynamic : 来自MSDN关于dynamic文章:

At compile time, an element that is typed as dynamic is assumed to support any operation. 在编译时,假定键入为动态的元素支持任何操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM