运行基于代码的不同类型

时间:2017-11-14 12:40:46

标签: c#

我想用我的 Piece 类的子类型对象为我的WPF-App调用一个方法。我的问题是子类型对象具有比 Text 对象更多的属性。

你知道一种比我在 FillForm 示例中更好地应对这种情况的方法吗?

namespace Namespace
{
    public abstract class Piece
        {
            public int id { get; set; }
            public string title { get; set; }
            public string description { get; set; }

        }

        public class Text : Piece
        {

        }

        public class Image: Piece{
             public string filePath { get; set; }
            public string fileformat { get; set; }
        }

        public class Video : Image
        {

        }   
    }
}

示例方法:

public void FillForm(Piece currentPiece)
{    
            pieceIdTextBox.Text = currentPiece.id.ToString();
            pieceNameTextBox.Text = currentPiece.title;
            pieceDescriptionTextBox.Text = currentPiece.description;
            if (!currentPiece.GetType().ToString().Equals("Namespace.Text"))
            {
                pieceFileSelectURLTextBlock.Text = (currentPiece as Namespace.Image).filePath;
                SetPreviews((currentPiece as Namespace.Image).filePath);
            }

}

谢谢!

2 个答案:

答案 0 :(得分:2)

为什么不将方法更改为以下类型安全

public void FillForm(Piece currentPiece)
{    
    pieceIdTextBox.Text = currentPiece.id.ToString();
    pieceNameTextBox.Text = currentPiece.title;
    pieceDescriptionTextBox.Text = currentPiece.description;
    if (currentPiece as Namespace.Image imagePiece)
    {
        pieceFileSelectURLTextBlock.Text = imagePiece.filePath;
        SetPreviews(imagePiece.filePath);
    }
}

答案 1 :(得分:0)

做一个安全播报:

public void FillForm(Piece currentPiece)
{    
            pieceIdTextBox.Text = currentPiece.id.ToString();
            pieceNameTextBox.Text = currentPiece.title;
            pieceDescriptionTextBox.Text = currentPiece.description;

            var imagePiece = currentPiece as Image;
            if(imagePiece != null)
                pieceFileSelectURLTextBlock.Text = imagePiece .filePath;
                SetPreviews(imagePiece .filePath);
            }

}