如何在运行时获得对实例的引用
本文关键字:实例 引用 运行时 | 更新日期: 2023-09-27 17:54:52
我正在使用第三方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; }
}
}
在不改变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);
根据您在其他回答中的评论,采用反射方法。总的来说,这是一个坏主意,原因很明显。
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");
}
我正在尝试一种完全不同的方法,并使用静态方法来检索我的上下文,我不完全确定这样做的后果,但到目前为止它正在工作。
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; }
}