![](/img/trans.png)
[英]Unable to cast the type 'System.String' to type 'System.Object'
[英]Cannot convert 'System.Object[]' to the type 'System.String[]'
您是否有其他想法来获取此数据列表?
我想展示我的所有代码,因为我认为这对您来说更容易。 在此代码中,您可以看到我如何与角色文件连接。
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.Interop.Security.AzRoles;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Collections.Generic;
namespace Authman
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// See the following table for other sample connection strings.
string connectionString = @"msxml://c:\plik.xml";
AzAuthorizationStoreClass azStore = new AzAuthorizationStoreClass();
azStore.Initialize(0, connectionString, null);
IAzApplication2 azApplication = azStore.OpenApplication2("SatheeshApp", null);
IAzClientContext3 clientContext = (IAzClientContext3)azApplication.InitializeClientContextFromToken((ulong)WindowsIdentity.GetCurrent().Token, null);
// Use the default application scope.
string[] roles = (string[])clientContext.GetRoles("");
foreach (string role in roles)
{
Span3.InnerHtml += role.ToString() + "</br>";
}
}
}
}
使用Cast<string>()
方法。 这与协方差/相反。 您需要转换数组中的每个项目(这是Cast
方法的作用),而不是整个数组。 如果确实需要将其转换为另一个字符串数组,则可以使用ToArray
方法,但是由于这里只使用了foreach
,因此不需要。
foreach(string role in clientContext.GetRoles("").Cast<string>())
{
//use role
}
您需要添加using System.Linq
以获取Cast
扩展方法。
string[] roles = clientContext.GetRoles("").Cast<string>().ToArray();
using System.Linq;
string[] roles = someObjectArray.OfType<object>().Select(o => o.ToString()).ToArray();
希望这可以帮助。
object[] roles=clientContext.GetRoles("");
foreach(object role in roles)
{
Span3.InnerHtml + = role.ToString() + "</br>";
}
为什么需要将数组强制转换为string[]
? 您可以使用它而无需投射。
您可以将其强制转换为object [],但错误表明它已被替代。
object[] roles = (object[])clientContext.GetRoles("");
foreach(object role in roles)
{
Span3.InnerHtml += role.ToString() + "</br>";
}
正如其他人指出的那样, clientContext.GetRoles("").Cast<string>().ToArray()
可以解决。
假设转换合法时会发生什么。 您有一个list listOfAnimals。
List<Cow> listOfCows = GetListOfCows();
listOfAnimals = listOfCows;
//After some lines of code
List<Tiger> listOfTiger = GetListOfTigers();
listOfAnimals.Add(listOfTiger); //Epic fail.
您可能不小心将Tiger
添加到Cow
列表中。 这是错误和危险的。 CLR不允许您在代码中引入此类错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.