C#
一种面向对象的类型安全的编程语言,它起源于 C 语言系列,包括对面向组件的编程的支持。
140 个问题
大家好,
我正在尝试为能够获取属性值并将其缓存以供将来引用的属性创建自定义属性。我设法让它在支持 Lazy<IWebElement 的情况下工作>如下所示:
protected virtual IWebElement CajaModal
{
get
{
if (lazyModal == null || !lazyModal.IsValueCreated)
{
lazyModal = new Lazy<IWebElement>(() => driver.FindElements(By.ClassName("ui-dialog"))
.Where(m => m.Displayed)
.First(m => m.FindElement(By.ClassName("ui-dialog-title")).Text == TituloModal),
LazyThreadSafetyMode.PublicationOnly);
}
try
{
return lazyModal.Value;
}
catch (InvalidOperationException)
{
throw new NoSuchElementException("El Modal no existe en el DOM");
}
}
}
我想做的是创建一个自定义属性,例如 [CacheWebElement] 并让 c# 为我制作它。我尝试过这段不完整的代码:
[System.AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
sealed class CachedWebElementAttribute : Attribute
{
// See the attribute guidelines at
// http://go.microsoft.com/fwlink/?LinkId=85236
private readonly Lazy<IWebElement> lazy;
// This is a positional argument
public CachedWebElementAttribute([CallerMemberName] string propertyName = null)
{
var property = GetType().GetProperty(propertyName);
lazy = new Lazy<IWebElement>(() => (IWebElement)property.GetMethod,
LazyThreadSafetyMode.PublicationOnly);
//(IWebElement)property.GetGetMethod().CreateDelegate((IWebElement) => lazy.Value);
}
}
但我不知道该怎么做。
因此,回顾一下,我想创建一个 [CacheWebElement] 属性,该属性将执行以下操作:
这样的事情甚至可能吗?有没有更好的方法?缓存一些属性将是我的应用程序向前迈出的一大步。
感谢您抽出宝贵时间接受采访
Note:此问题总结整理于: How to create a Custom Attribute capable of caching a readonly property?
对于您的第一个问题,也许此链接可以提供一些帮助: 在调用异步委托时防止 Lazy<>T 缓存异常 对于第二个问题,是否要为属性中的属性设置值? 这似乎是不可能的(也可能是我缺乏知识),我试图找到这样的方法,但一无所获。 是否可以在编写属性时定义属性,然后在代码中检查属性的值,如果它不符合预期,则使用反射获取属性中的属性值并将其分配给目标属性? 像这样:
if (xxx)
{
PropertyInfo propertyInfo = xxx;
CachedWebElementAttribute attribute =(CachedWebElementAttribute) Attribute.GetCustomAttribute(propertyInfo, typeof(CachedWebElementAttribute));
if (attribute != null)
{
//propertyInfo.SetValue(myClass, attribute.Lazy, null); // null means no indexes
//Here is the body of the code. We can get the property directly, so we can assign values directly without using reflection.
lazyModal = attribute.Lazy;
}
}
如果回复有帮助,请点击“接受答案”并点赞。
注意:如果您想接收此线程的相关电子邮件通知,请按照我们文档中的步骤启用电子邮件通知。