可能會使用System.Runtime.Remoting
層次結構下的*Services
對象之一,如mtijn所示。但是,您的對象模型中存在深層問題。對物體承擔雙重責任是不好的做法,難以保持和難以理解。爲什麼不公開一個專用的'遠程'對象;下面的示例演示了:
class Program
{
static void Main(string[] args)
{
InitializeRemoting();
var remote = GetRemotingObject("localhost");
var local = new LocalClass();
remote.SomeMethod();
local.SomeMethod();
Console.ReadLine();
}
static void InitializeRemoting()
{
var c = new TcpServerChannel(9000);
ChannelServices.RegisterChannel(c, false);
WellKnownServiceTypeEntry entry = new WellKnownServiceTypeEntry
(
typeof(RemoteClass),
"LocalClass", // Lie about the object name.
WellKnownObjectMode.Singleton
);
RemotingConfiguration.RegisterWellKnownServiceType(entry);
}
static LocalClass GetRemotingObject(string serverName)
{
TcpClientChannel channel = new TcpClientChannel("tcp-client", new BinaryClientFormatterSinkProvider());
ChannelServices.RegisterChannel(channel, false);
return (LocalClass)Activator.GetObject
(
typeof(LocalClass), // Remoting will happily cast it to a type we have access to.
string.Format("tcp://{0}:9000/LocalClass", serverName)
);
}
}
public class LocalClass : MarshalByRefObject
{
public void SomeMethod()
{
OnSomeMethod();
}
protected virtual void OnSomeMethod()
{
// Method called locally.
Console.WriteLine("Local!");
}
}
// Note that we don't need to (and probably shouldn't) expose the remoting type publicly.
class RemoteClass : LocalClass
{
protected override void OnSomeMethod()
{
// Method called remotely.
Console.WriteLine("Remote!");
}
}
// Output:
// Remote!
// Local!
編輯:直接回答你的問題,即使你正在努力實現的是不好的做法,複製我的代碼,只需提供virtual bool IsLocal { get { return true; } }
上的本地類並覆蓋其在遠程類上。然後,您可以在if語句中使用該屬性。
編輯:如果你的服務器和你的客戶需要共享完全相同的類的實例,你應該使用Facade Pattern。例如:
class CommonImplementation
{
public static readonly CommonImplementation Instance = new CommonImplementation();
private CommonImplementation() { }
public void SomeMethod(string someArg, bool isServerCall)
{
if (isServerCall)
{
Console.WriteLine("Remote! {0}", someArg);
}
else
{
Console.WriteLine("Local! {0}", someArg);
}
}
}
// These two classes are the facade.
public class LocalClass : MarshalByRefObject
{
public virtual void SomeMethod(string someArg)
{
CommonImplementation.Instance.SomeMethod(someArg, false);
}
}
class RemoteClass : LocalClass
{
public override void SomeMethod(string someArg)
{
CommonImplementation.Instance.SomeMethod(someArg, true);
}
}
不,那不是幫助我的人。((我有RemoteClass只有一個實例,它是在服務器和客戶端使用,但它只是一個 – Vasya
@ Praetor12它確實幫助最初的例子,Facade模式是你在進行軟件開發時應該理解的東西,你應該花更多的精力來解決這樣的簡單問題,無論如何,我提供了將所有調用轉發給共享實例的代碼。 –