将对象作为ref参数传递给泛型方法

本文关键字:参数传递 泛型方法 ref 对象 | 更新日期: 2023-09-27 18:10:17

我创建了一个泛型方法,我想通过对该方法的引用传递一个对象来填充一些属性。它编译和运行没有问题,但是对象没有被填充。

my generic method

public static void SplitAddress<T>(ref T ob, string addressToSplit) where T : Address
    {
        //ptr : Postcode, Town, Region
        var ptr = addressToSplit.Split(new char[] { '-' }, 2, StringSplitOptions.RemoveEmptyEntries).ToList();
        var pt = ptr[0].Split(new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries).ToList();
        if (ptr.Count == 2)
        {
            ob.Region = ptr[1];
        }
        for (int x = 0; x < pt.Count; x++)
        {
            switch (x)
            {
                case 0:
                    {
                        ob.PostCode = pt[x];
                        break;
                    }
                case 1:
                    {
                        ob.Town = pt[x];
                        break;
                    }
            }
        }
    }

要传递的对象

class Merchant : Address
{
    public int MeId { get; set; }
    public int HoId { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
    public string Address { get; set; }
    public string PostCode { get; set; }
    public string Town { get; set; }
    public string Region { get; set; }
    public string VatNr { get; set; }
    public string TRSshopId { get; set; }
}

Address类

abstract class Address
{
    public string PostCode;
    public string Town { get; set; }
    public string Region { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
    public string Adrress { get; set; }
}

方法调用

Methods.SplitAddress<Merchant>(ref me, row.Cells[i].Text);

我可以为两种不同的对象类型创建两个重载方法,但它们将重复相同的代码,这是我想要避免的。它看起来很奇怪,但是例如"Postcode"正在被填充,但是当我将鼠标悬停在"ob"上时,属性仍然为空。

将对象作为ref参数传递给泛型方法

EDIT

正如@Lee敏锐地注意到的,你是Member中隐藏了 Address的属性。因为你的泛型方法被限制为类型Address的成员,你的代码实际上是改变隐藏的Address类的属性,而不是Merchant类的属性,所以如果你有一个类型Merchant的变量,你就看不到这些变化。如果将Member转换为Address,您将看到这些值。只要从Merchant中删除这些属性,就可以了。

注。Member 继承Address形式似乎是错误的——成员地址,如果不是地址。更好的设计是:

class Merchant
{
    public int MeId { get; set; }
    public int HoId { get; set; }
    public string Name { get; set; }
    public Address Address { get; set; }
    public string VatNr { get; set; }
    public string TRSshopId { get; set; }
}

原始回答

我想通过这个方法的引用传递一个对象来填充一些属性

因为Address是一个类,你不需要使用ref。引用类型的参数将包含对传入变量的相同对象的引用,因此您可以更改该对象的属性值,而调用方法将看到更改。ref允许您做的主要事情是将引用更改为不同的对象,这是您没有做的,因此使用ref不会改变您正在尝试做的事情。

我建议你在调试器中运行它,以确保你的if块以你期望的方式执行。(例如,ptr.Count == 2是真的吗?可以大于2吗?)

你的整个for块也可以减少到:

if(pt.Count > 0)  ob.PostCode = pt[0];
if(pt.Count > 1)  ob.Town = pt[1];