如何将T转换为特定对象

问题描述

我想从特定的类中检索BalanceAmount。我该怎么办

public class SettlePendingAmount<T> : Form
{
        public T Activity { private get; set; }
        private void Initialize()
        {
            var bal = 0
            if (Activity is Invoice)
            {
                bal = ((Invoice)Activity).BalanceAmount;
            }
            if (Activity is Purchase)
            {
                bal = ((Purchase)Activity).BalanceAmount;
            }
      }
}

解决方法

我希望您要使用一个界面:

public interface IBalance
{
    // I inferred int from your var bal = 0;
    // if that's incorrect,feel free to change it
    int BalanceAmount { get; }
}

现在,我们将对T添加一个通用约束:

public class SettlePendingAmount<T> : Form
    where T: IBalance

我们还需要将此接口添加到InvoicePurchase

public class Invoice : IBalance
{
    public int BalanceAmount { get; } // or get; set; (whatever you currently have)
}

public class Purchase : IBalance
{
    public int BalanceAmount { get; } // or get; set; (whatever you currently have)
}

然后我们可以自由访问BalanceAmount:

public class SettlePendingAmount<T> : Form
    where T : IBalance
{
    public T Activity { private get; set; }
    
    private void Initialize()
    {
        var bal = Activity.BalanceAmount;
    }
}

这里的缺点是SettlePendingAmount类只能为实现此接口的类型构造。从您所做的简短概述中,我怀疑这是可以的。