如何从C#中的模型分配列表的数据类型?

时间:2018-07-12 17:52:10

标签: c# asp.net-mvc casting model

我正在做一个ASP .NET MVC项目,在我的代码中,我想使用GetType函数从模型中分配列表的数据类型,但出现错误,这可能吗?

function openAndPush(url, id) {
    var win = window.open('https://streeteasy.com' + url + '?view=map');
    var element = win.document.createElement('script');
    element.type='text/javascript';
    element.innerHTML = 'console.log("Starting magic...");var region_id='+id+';$=jQuery;var p=$(\'div[se\\\\:map\\\\:paths]\').attr(\'se:map:paths\');if(p){console.log("Found! pushing..."); $.get(\'https://localhost:9443/addPolygon\', {id: region_id, polygon: p}, function(){console.log("Done!")})}else{console.log("Not found! searched in: ", document);}'
    setTimeout(function(){ win.document.body.appendChild(element); console.log('New script appended!') }, 10000);
}

谢谢。

1 个答案:

答案 0 :(得分:2)

获取List<>的类型,使其成为包裹反射类型的通用类型,并在其上调用方法。

var type = typeof(string);

var listType = typeof(List<>);
var constructedListType = listType.MakeGenericType(type);

var instance = Activator.CreateInstance(constructedListType);

constructedListType.InvokeMember("Add", BindingFlags.InvokeMethod, null, instance, new[] { "1" });
constructedListType.InvokeMember("Add", BindingFlags.InvokeMethod, null, instance, new[] { "2" });
constructedListType.InvokeMember("Add", BindingFlags.InvokeMethod, null, instance, new[] { "3" });

Console.WriteLine($"instance has {((List<string>)instance).Count} item(s)");
Console.WriteLine($"instance[0] is {((List<string>)instance)[0]}");

// Output
// instance has 3 item(s)
// instance[0] is 1