簡體   English   中英

C#在內部傳遞具有相同屬性的ref不同類型的對象,並在沒有接口的情況下填充它們

[英]C# pass by ref different types of object that have the same properties inside and populate them without interface

如何通過ref內部具有相同屬性的不同類型的對象進行傳遞,並在沒有接口的情況下填充它們。

在我的應用程序中,完全不同的類型具有一些共同的屬性。 假設此屬性是雙精度數組。

double[] samples;

現在,我必須為20個對象填充這些樣本。 我無權訪問此對象的類定義,因此無法創建接口或使它們從基類繼承。

如何使用一個我調用的方法和這個方法來填充我的所有屬性。

我想要一種這樣的方法:

private static void FillSamples(ref WhoKnowsWhat dataType, MyObject theSamples)
{

for (int i = 0; i < sampleCount; i++)
                        {
                            dataType.SampleLength[i] = MyObject.X[i];
                            dataType.SampleValue[i]  = MyObject.y[i];
                        }
}

並用完全不同的類型來稱呼它。

FillSamples(ref BigStruct.OneTypeMine, theSamples);
FillSamples(ref BigStruct.AnotherTypeMine, theSamples);
FillSamples(ref BigStruct.HisType12345, theSamples);

然后,大結構應在最后填充這些樣本。

C#中有辦法嗎?

謝謝!

您可以使用dynamic關鍵字:

private static void FillSamples(dynamic dataType, MyObject theSamples)
{
    for (int i = 0; i < sampleCount; i++)
    {
        dataType.SampleLength[i] = MyObject.X[i];
        dataType.SampleValue[i]  = MyObject.y[i];
    }
}

編輯:

使用反射(如果不使用.Net 4.0或更高版本):

private static void FillSamples(object dataType, MyObject theSamples)
{
    Type t = dataType.GetType();
    var px = t.GetProperty("SampleLength");
    var py = t.GetProperty("SampleValue");

    for (int i = 0; i < sampleCount; i++)
    {
        px.SetValue(dataType, MyObject.X[i], null);
        py.SetValue(dataType, MyObject.Y[i], null);
    }
}

不知道它是否對您有幫助,但是您可以使用反射來找出對象在運行時支持哪些屬性(以及字段,方法等)。 例如,如果您想了解更多信息,請查看http://www.csharp-examples.net/reflection-property-names/

您可以使用動態對象。 定位動態對象的字段時應小心,因為在編譯時無法檢查它們。 請參閱下面的示例:

[TestFixture]
public class DynamicObjects
{
    [Test]
    public void Dynamic_Call()
    {
        dynamic obj1 = new Apple();
        obj1.Weight = 100;
        obj1.Color = "Red";

        dynamic obj2 = new Orange();
        obj2.Weight = 200;
        obj2.Width = 10;

        Assert.IsTrue(obj1.Weight < obj2.Weight);
    }
}

public class Apple
{
    public int Weight { get; set; }
    public string Color { get; set; }
}

public class Orange
{
    public int Weight { get; set; }
    public int Width { get; set; }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM