我已经创建了一个新的ListViewItem,它将一个统一化的对象分配给它的标记属性:
// Here, anonymous type object
newListViewItem.Tag = new { XPATH = FindXPath(node) };
我尝试恢复它的XPATH属性,如:
// Recover Tag property on myObj
Object myObj = myListView.Items[0].Tag;
// Store XPATH property
string xpath = myObj.XPATH;
但我错了:Severity Code Description Project File Line Status suppressed. Error CS1061 'object' does not contain a definition for 'XPATH' nor is there any method of extension 'XPATH' that accepts a first argument of type 'object' (is there any using directive or an assembly reference?)
我在声明的对象中尝试过同样的方法,它可以工作,但是未定义的对象不能工作。示例代码工作:
// type object (class Xpath)
newListViewItem.Tag = new Xpath(FindXPath(node));
Xpath myObj = (Xpath)myListViewMostrarXML.Items[0].Tag;
string xpath = myObj.XPATH;
有什么想法吗?
发布于 2018-04-15 06:36:53
您可以使用动态键入来完成以下操作:
// NOTE: NOT RECOMMENDED; SEE BELOW
// Populate the tag as before
newListViewItem.Tag = new { XPATH = FindXPath(node) };
// Recover Tag property using a variable of type dynamic
dynamic myObj = myListView.Items[0].Tag;
string xpath = myObj.XPATH;
然而,我强烈建议你不要这样做。您只需要使用动态类型来避免声明几个类,每个类无论如何都很容易创建。例如:
public class XPathTag
{
public string XPath { get; set; }
}
// Populate the tag using the class. You could add a constructor
// accepting the XPath if you wanted
newListViewItem.Tag = new XPathTag { XPath = FindXPath(node) };
// Recover Tag property using a variable of type dynamic
XPathTag tag = (XPathTag) myListView.Items[0].Tag;
string xpath = tag.XPath;
现在,如果您从一个具有非XPathTag标记的控件中获取一个标记,您将看到一个异常,它准确地指示出了什么问题。此外,在访问属性时不可能获得打印输出,就像使用动态类型解决方案一样.编译器将检查您如何使用该标记。
从根本上说,C#几乎完全是一种静态类型的语言。接受这一点,并创建您希望能够可靠地引用特定数据集的类型。虽然仍然存在可能失败的类型,但这是一个潜在的故障点,它将比动态类型方法容易得多。
发布于 2018-04-14 22:51:02
首先,该对象不是未初始化的,您正在创建一个匿名类型并将其分配给Tag
属性。标记的类型已经是对象,所以您实际上不需要将它转换为object
。
您希望稍后访问该属性,但会得到一个错误,因为该属性没有在Object
类上声明。C#是一种类型安全的语言,这意味着如果一个成员(方法或属性)不是在一个类型上声明的,就不能访问它。
为了访问它,您必须将Tag
属性转换为具有Path
属性的类型,但您不能这样做,因为您不知道它的名称。它实际上不是匿名的,它有一个编译器生成的名称,但对您来说是不可见的。因此,您需要创建一个具有相关属性的类型,并使用它而不是匿名类型。
https://stackoverflow.com/questions/49836818
复制相似问题