在运行时c#反射时强制转换列表类型

本文关键字:转换 列表 类型 运行时 反射 | 更新日期: 2023-09-27 18:15:45

我一直在使用反射,但它对我来说还是很新的。所以下面这条线是正确的。它返回一个DataBlockOne

的列表
 var endResult =(List<DataBlockOne>)allData.GetType() 
.GetProperty("One")
.GetValue(allData);

但是直到运行时我才知道myType。因此,我的想法是下面的代码从返回的对象中获取类型,并将该类型转换为DataBlockOne的列表。

List<DataBlockOne> one = new List<DataBlockOne>();
one.Add(new DataBlockOne { id = 1 });
List<DataBlockTwo> two = new List<DataBlockTwo>();
two.Add(new DataBlockTwo { id = 2 });
AllData allData = new AllData
{
    One = one,
    Two = two
};
var result = allData.GetType().GetProperty("One").GetValue(allData);
Type thisType = result.GetType().GetGenericArguments().Single();

注意我不知道下面的列表类型。我只是用DataBlockOne作为一个例子

 var endResult =(List<DataBlockOne>)allData.GetType() // this could be List<DataBlockTwo> as well as List<DataBlockOne>
.GetProperty("One")
.GetValue(allData);

我需要强制转换,这样我可以稍后搜索列表(如果不强制转换返回的对象,这将会出错)

if (endResult.Count > 0)
{
    var search = endResult.Where(whereExpression);
}

我混淆了类类型和列表中使用的类型。有人能指出我在正确的方向得到一个类型在运行时,并设置为我的类型的列表?

类定义:

public class AllData
{
    public List<DataBlockOne> One { get; set; }
    public List<DataBlockTwo> Two { get; set; }
}
public class DataBlockOne
{
    public int id { get; set; }
}
public class DataBlockTwo
{
    public int id { get; set; }
}

在运行时c#反射时强制转换列表类型

您可能需要这样做:

var endResult = Convert.ChangeType(allData.GetType().GetProperty("One").GetValue(allData), allData.GetType());

只是猜测,从2013年开始c#就不工作了,请不要拍摄:)

您可能想要这样的内容:

static void Main(string[] args)
{
    var one = new List<DataBlockBase>();
    one.Add(new DataBlockOne { Id = 1, CustomPropertyDataBlockOne = 314 });
    var two = new List<DataBlockBase>();
    two.Add(new DataBlockTwo { Id = 2, CustomPropertyDatablockTwo = long.MaxValue });
    AllData allData = new AllData
    {
        One = one,
        Two = two
    };
    #region Access Base Class Properties
    var result = (DataBlockBase)allData.GetType().GetProperty("One").GetValue(allData);
    var oneId = result.Id;
    #endregion
    #region Switch Into Custom Class Properties
    if (result is DataBlockTwo)
    {
        var thisId = result.Id;
        var thisCustomPropertyTwo = ((DataBlockTwo)result).CustomPropertyDatablockTwo;
    }
    if (result is DataBlockOne)
    {
        var thisId = result.Id;
        var thisCustomPropertyOne = ((DataBlockOne)result).CustomPropertyDataBlockOne;
    }
    #endregion

    Console.Read();
}

public class AllData
{
    public List<DataBlockBase> One { get; set; }
    public List<DataBlockBase> Two { get; set; }
}
public class DataBlockOne : DataBlockBase
{
    public int CustomPropertyDataBlockOne { get; set; }
}
public class DataBlockTwo : DataBlockBase
{
    public long CustomPropertyDatablockTwo { get; set; }
}
public abstract class DataBlockBase
{
    public int Id { get; set; }
}
相关文章: