0
タイトルで、それから値を得ることが本当の私は必要なものを説明したが、ここでのサンプルではありません。ここでキャストオブジェクト・タイプ値とは、リフレクション
public class Car {
public int CarId { get; set; }
public string Name { get; set; }
public string Model { get; set; }
public string Make { get; set; }
}
:これは私のモデルは
です論理:
class Program {
static void Main(string[] args) {
var cars = new List<Car> {
new Car { CarId = 1, Make = "Foo", Model = "FooM", Name = "FooN" },
new Car { CarId = 2, Make = "Foo2", Model = "FooM2", Name = "FooN2" }
}.AsQueryable();
doWork(cars.GetType(), cars);
}
static void doWork(Type type, object value) {
if (isTypeOfIEnumerable(type)) {
Type itemType = type.GetGenericArguments()[0];
Console.WriteLine(
string.Join<string>(
" -- ", itemType.GetProperties().Select(x => x.Name)
)
);
//How to grab values at the same order as properties?
//E.g. If Car.Name was pulled first,
//then the value of that property should be pulled here first as well
}
}
static bool isTypeOfIEnumerable(Type type) {
foreach (Type interfaceType in type.GetInterfaces()) {
if (interfaceType.IsGenericType &&
interfaceType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
return true;
}
return false;
}
}
私がここで行うことは意味をなさないかもしれませんが、私はこの種の操作が必要です。私はType
とObject
を持っており、それからテーブルを作る必要があります。この例では、doWork
メソッドは、私の実際の例で扱っているものとかなり同じです。
プロパティ名を取得できましたが、value
パラメータから値を取得する方法が見つかりませんでした。
誰でも?
私はあなたの質問を理解することはできませんが、このような試みをしましたか? 'obj.GetType()。GetProperties()。Select(pi => new {Name = pi.Name、Value = pi.GetValue(obj、null)})' –
@ L.Bありがとう!私が受け入れることができるようにこれを答えとして書くことができますか? – tugberk