如何在运行时获取对实例的引用?

时间:2016-07-04 18:02:16

标签: c#

我正在使用第三方SDK,它允许我通过创建对象来自定义它。在我的对象内部,我可以做任何我想要的,它提供了将我自己的配置传递给它的能力,但我不能将一个对象(引用)传递给它。在我的情况下,我有一个上下文对象,我需要获取引用。 如何在运行时获取对实例的引用? 下面我试图模拟这个问题:

using System;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            var runtime = new Runtime();
        }
    }

    class Runtime
    {
        private MyContext myContext;

        public Runtime()
        {
            myContext = new MyContext();

            //cant pass my object in
            var myobject = new ClassThatNeedsAReferenceToMyContext();

            if(myobject.theContext == myContext)
            {
                Console.WriteLine("Yahoo");
            }
        }
    }

    class MyContext
    {

    }

    class ClassThatNeedsAReferenceToMyContext
    {
        public ClassThatNeedsAReferenceToMyContext()
        {
            //do something here to get a reference to myContext
        }
        public MyContext theContext { get; private set; }
    }
}

3 个答案:

答案 0 :(得分:0)

在不更改ClassThatNeedsAReferenceToMyContext类型的情况下,您只需将上下文分配给属性:

var myobject = new ClassThatNeedsAReferenceToMyContext();

myobject.theContext = myContext;

当然,这样做会使以下测试变得多余,因为您可以确定myobject.theContext == myContext

除此之外,您还可以使ClassThatNeedsAReferenceToMyContext将上下文作为构造函数参数。这使得依赖更加明确:

class ClassThatNeedsAReferenceToMyContext
{
    public ClassThatNeedsAReferenceToMyContext(MyContext context)
    {
        this.theContext = context;
    }

    public MyContext theContext { get; set; }
}

之后,您可以将上下文传递给构造函数:

var myobject = new ClassThatNeedsAReferenceToMyContext(myContext);

答案 1 :(得分:0)

根据您在其他答案中的评论的反思方法。总的来说,出于明显的原因,这是一个坏主意。

Type type = typeof(ClassThatNeedsAReferenceToMyContext);
PropertyInfo property = type.GetProperty("theContext");
MethodInfo setter = property.GetSetMethod(nonPublic: true);

MyContext mycontext = new MyContext();
ClassThatNeedsAReferenceToMyContext myobject = new ClassThatNeedsAReferenceToMyContext();
setter.Invoke(myobject, new[] { mycontext });

if (myobject.theContext == mycontext)
{
    Console.WriteLine("Yahoo");
}

答案 2 :(得分:0)

I am trying a completely different approach and using a static method to retrieve my context, I am not completely sure about the consequences of this, but so far it is working.

class Runtime
{
    private MyContext myContext;

    public static Mycontext GetMyContext()
    {
        return myContext;
    }
    public Runtime()
    {
        myContext = new MyContext();

        //cant pass my object in
        var myobject = new ClassThatNeedsAReferenceToMyContext();

        if(myobject.theContext == myContext)
        {
            Console.WriteLine("Yahoo");
        }
    }
}

class ClassThatNeedsAReferenceToMyContext
{
    public ClassThatNeedsAReferenceToMyContext()
    {
        //do something here to get a reference to myContext
         theContext = Runtime.GetMyContext();
    }

    public MyContext theContext { get; private set; }
}