我可以定义一个对类类型和类实例都可用的属性吗
本文关键字:实例 属性 类型 一个 我可以 定义 | 更新日期: 2023-09-27 18:25:31
我有一个基类的接口,从基类继承的每个类都应该有一个标识字段,该字段告诉应用程序它是什么类型的对象
我想用两种不同的方式使用这个属性:
不创建对象的实例
if (someValue == TestA.Id)
return new TestA();
elseif (someValue == TestB.Id)
return new TestB();
并且作为接口的一个属性
void DoSomething(ITest testObject)
{
SomeValue = testObject.Id;
}
有没有一种简单的方法可以在接口中定义Id
字段,但仍然可以在不创建类实例的情况下使用它?
现在我正在使用以下代码。我可以在返回const字符串的接口中添加一个只读的Id
属性,但我希望有一种我不知道的更简单的方法。
public interface ITest
{
}
public class TestA : ITest
{
public const string Id = "A";
}
简而言之,没有
为了能够做到这一点,您需要能够将其指定为接口上的实例属性(并在实例中实现),以及类型上的静态属性。
编译器不允许你这样做。
您可以将其放在接口中,也可以将其作为静态属性。类似于:
interface IInterface { Id { get; } }
class Class : IInterface
{
public static Id { get { return 1; } }
public Id { get { return Class.Id; } }
}
Rachel,我也遇到过类似的问题,我总是(不幸的是)让工厂代码依赖于反射来获得每个具体类型的"TypeID"公共静态属性。。。从而使契约接口成为一个额外的方面,但在C#接口代码中没有它。
您可以这样做。
public interface ITest
{
SomeValue Id{ get;}
}
public class TestA : ITest
{
public SomeValue Id
{
get {return TestA.StaicId; }
}
public static SomeValue StaticId
{
get {return "This is TestA";}
}
}
if (someValue == TestA.StaticId)
return new TestA();
使用属性怎么样?这里有一个可以做什么的小例子:
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public class IdAttribute : Attribute
{
public IdAttribute(string id)
{
this.Id = id;
}
public string Id { get; set; }
}
public interface IMyInterface
{
}
public abstract class BaseClass : IMyInterface
{
public static string GetId<T>() where T : IMyInterface
{
return ((IdAttribute)typeof(T).GetCustomAttributes(typeof(IdAttribute), true)[0]).Id;
}
}
[Id("A")]
public class ImplA : BaseClass
{
}
[Id("B")]
public class ImplB : BaseClass
{
}
internal class Program
{
private static void Main(string[] args)
{
var val1 = BaseClass.GetId<ImplA>();
var val2 = BaseClass.GetId<ImplB>();
Console.ReadKey();
}
}