类似LINQ的C#中绑定/链接的对象/类

本文关键字:链接 对象 LINQ 类似 绑定 | 更新日期: 2023-09-27 18:25:51

也许这是一个新手问题,但有人能解释一下绑定/链接类(我不知道它们的真名)是如何形成的吗?示例可以是LINQ TO XML

当我有下面的代码:

XDocument doc = XDocument.Load("...");
XElement element = doc.Element("root");
element.SetAttribute("NewAttribute", "BlahBlah");
doc.Save("...");

我只更改element变量(我不需要在doc中更新它,因为它被引用了)。如何创建这样的类?

[edit]
我尝试了@animanionline的代码,它可以

A a = new A();
B b = a.B(0);
b.Name = "asd";
Console.WriteLine(a.Bs[0].Name); // output "asd"

但是,告诉我们上面和下面的代码有什么区别?

List<string> list = new List<string>();
list.Add("test1");
list.Add("test2");
var test = list.FirstOrDefault();
test = "asdasda";
Console.WriteLine(list[0]); // output "test1" - why not "asdasda" if the above example works???

类似LINQ的C#中绑定/链接的对象/类

doc.Element是一个方法,它返回对具有指定XName的第一个子元素(按文档顺序)的引用。

考虑这个例子:

public class A
{
    public A()
    {
        this.Bs = new List<B>();
        this.Bs.Add(new B { Name = "a", Value = "aaa" });
        this.Bs.Add(new B { Name = "b", Value = "bbb" });
        this.Bs.Add(new B { Name = "c", Value = "ccc" });
    }
    public List<B> Bs { get; set; }
    public B B(int index)
    {
        if (this.Bs != null && this.Bs[index] != null)
            return this.Bs[index];
        return null;
    }
}
public class B
{
    public string Name { get; set; }
    public string Value { get; set; }
}

用法:

A a = new A();
var refToA = a.B(0);
refToA.Value = "Some New Value";
foreach (var bs in a.Bs)
    System.Console.WriteLine(bs.Value);

解释:

正如您所看到的,B()方法返回对a类中列表项的引用,更新它也会更改a.bs列表中的值,因为它是同一个对象。

认为我理解你的要求。我的回答的有效性完全基于这个前提D


类成员不必是基元类型,它们也可以是其他类。

简单示例

给定两个类SimpleXDocument和SimpleXElement,请注意SimpleXDocuments有一个类型为SimpleXElement:的成员/公开属性

public Class SimpleXDocument
{
    private SimpleXElement _element;
    public SimpleXDocument(){ this._element = null;}
    public SimpleXDocument(SimpleXElement element){this._element = element;}
    public SimpleXElement Element
    {
        get{return this._element;}
        set{this._element = value;}
    }
}
Public Class SimpleXElement
{
    private String _value;
    public SimpleXElement(){this._value = String.Empty;}
    public SimpleXElement(String value){this._value = value;}
    public String Value
    {
        get{return this._value;}
        set{this._value = value;}
    }
}

SimpleXDocument引用了它自己的SimpleXElement类型的成员。你可以做这样的事情:

SimpleXDocument doc = new SimpleXDocument();
doc.Element = new SimpleXElement("Test 1");
SimpleXElement element = new SimpleXElement();
element.Value = "Test 2";
doc = New SimpleXDocument(element);
SimpleXElement anotherElement = new SimpleXElement("another test");
doc.Element = anotherElement;
doc.Element.Value = "yet another test";
anotherElement.Value = "final test"; //N.B. this will update doc.Element.Value too!

据我所知,u不需要对元素的引用,而是位于引用后面的对象的副本。

我认为这个答案会帮助你:https://stackoverflow.com/a/129395/1360411