将对象传递给方法并确定类型

时间:2015-07-29 21:13:09

标签: c#

我不确定提出这个问题的最好方法,但我想将一个对象传递给一个方法,并根据对象的类型通过该函数使用该对象。可能还有另一种解决办法让我解释一下情况。

我有一个客户向我返回两个对象(Foo和Bar)。但是,这些对象几乎相同,所以我正在尝试编写一个函数来读取数据。

以下是我想要做的代码片段,但这显然不起作用。

        public static void MyFunction(object obj)
        {

            object order = null;
            if (typeof(Foo) == obj.GetType())
            {
                order = obj as Foo;
            }
            else
                order = obj as Bar;

            // get data from order

        }

非常感谢任何帮助或指示。

3 个答案:

答案 0 :(得分:1)

我怀疑我们作为一个社区可以评论的场景还有很多,例如评论中提到的界面的使用。但是,只知道我们所知道的东西,你可以尝试一些简单的东西,比如:

    public static void MyFunction(object obj)
    {
        Foo foo;
        Bar bar;

        if ((foo = obj as Foo) != null)
             //Work with foo here.
        else if ((bar = obj as Bar) != null)
             //Work with bar here
    }

答案 1 :(得分:0)

如果你真的需要有一个FooBar的通用界面,你就不能让他们共享一个基类或实现一个界面(也许他们会在一个你不拥有的程序集,你可以使用适配器模式。

您可以创建一个抽象基类来定义您需要访问的所有属性,然后为您需要操作的每个对象从该基类派生一次。然后,您只需为您拥有的对象类型创建正确的适配器,传入适配器需要调整的对象,并将其存储到基类类型的引用中以供稍后使用。

您可以使用界面而不是抽象类来执行相同操作。

答案 2 :(得分:0)

你基本上有两个选项,它们都要求你有一些共性的元素,比如公共基类或接口声明......对于下面的例子,我使用了一个接口:

public interface IFooBar 
{
    ...
}

// Option 1: Just type the parameter to the interface (the simplest)
public static void MyFunction(IFooBar obj)
{
    // get data from order
}

// Option 2: Use a generic type parameter and constraint that it must 
// be of type IFooBar (this can be useful for certain reflection scenarios)
public static void MyFuntion<TObject>(TObject obj)
    where TObject: IFooBar
{
    // get data from order
}

// Option 2a: Same as Option 2 however we take advantage of the constraint 
// to inform the the compiler that TObject will have a default parameterless
// constructor so we can actually instantiate TObject
public static void MyFuntion<TObject>(TObject obj)
    where TObject: IFooBar, new()
{
    // get data from order
    ...

    // We can do this because of the new() constraint
    return new TObject();
}
相关问题