I have noticed the C# spec doesn't allow for fields in an interface, only methods or events.
Does this mean the only feasible way for me to implement a "field" is to do something like:
public interface Field
{
string S_set(string setTo);
string S_get();
}
public class FieldTest : Field
{
private string szStore;
public string S_get() { return szStore; }
public string S_set(string szSetTo) { szStore = szSetTo; }
public property Store {
get {
return S_get();
}
set {
S_set(value);
}
}
}
This is a bit messy, but it does work... The only messy part is that the S_get and S_set methods are publicly visible to other classes. But I assume there's no other way to implement a property/field in an interface?
I'm using interfaces for plugins and I want to be able to store simple metadata in the plugin accessible programatically via properties. (e.g. "bool pluginNeedsAdministratorRights" or "string pluginName") Setting up method calls just to retrieve static values seems kind of silly...
fm

1 answers
woops on the Public Property... lol ,public string.
answered 2 years ago by:
490
Well, you can't create an object of an interface type so it would be inappropriate for them to have 'state' i.e. instance fields.
Also interfaces cannot have static members of any description.
What you can do is to create a default implementation of an interface using extension methods (.NET 3.5). All classes implementing the interface can then share the same field if they don't want to implement their own field.
You can also implement the interface property using 'explicit interface implementation' so that it appears to be private but can in fact be accessed using an interface reference:
using System;
using FieldEx;
namespace FieldEx
{
// default implementation of IField
public static class Field
{
private static string szStore;
public static string S_get(this IField field)
{
return szStore;
}
public static void S_set(this IField field, string setTo)
{
szStore = setTo;
}
}
}
public interface IField
{
string S { get; set; }
}
public class FieldTest : IField
{
string IField.S
{
get { return this.S_get();}
set { this.S_set(value); }
}
}
class Test
{
static void Main()
{
IField ift = new FieldTest();
ift.S = "Hello";
Console.WriteLine(ift.S);
Console.ReadKey();
}
}
answered 2 years ago by:
17279
This post was imported from csharpfriends, if you have a similiar question please ask it again.
All previous members have been migrated, hope you enjoy the new platform!