Force an object to be called via its interface
How can I force an object to be called only via its interface? That can only accomplish via Access Modifier but in C# can't do.
I have:
public interface IProfile { string开发者_如何转开发 GetName(); }
public class Profile : IProfile {
public string GetName() { return "Linh"; }
}
I have a code section like that above. I put it in a class library after that I generate an assembly.
In a web project some programmers will add reference to that assembly. If they want to call Profile class then they must use IProfile interface as declaration below:
IProfile ip = new Profile();
ip.GetName();
But some careless programmers won't do so. They will use below way:
Profile pr = new Profile();
pr.GetName();
This is really simple. Use an explicit interface implementation:
public interface IProfile { string GetName(); }
public class Profile : IProfile
{
string IProfile.GetName() { return "Linh"; }
}
GetName
can now only be called through an interface reference.
You'll want to adopt a factory approach, like so:
using System;
using Ext;
namespace ConsoleApplication26
{
class Program
{
static void Main(string[] args)
{
IFoo foo = FooFactory.GetFoo();
}
}
}
// another project/dll
namespace Ext
{
public interface IFoo
{
void M ();
}
public static class FooFactory
{
public static IFoo GetFoo ()
{
return new Foo();
}
}
class Foo : IFoo
{
public void M () { }
}
}
If the question meant to be "How to force calling of interfaced methods only ?", then the answer could be: "Make the rest of methods private"
精彩评论