如何以字符串形式获取图像资源的名称
How to get the name of an image resource as a string
我尝试了几种方法来获取名称,包括调查 PropertyItems
和老式的 ToString()
方法来尝试获取图像资源的名称作为字符串。
我在资源文件中选择了一组图像,命名为。使用 resource.imageName
显示图像没有问题。我想尝试将 imageName
作为字符串来减少代码中其他地方的错误和拼写错误。
使用 resource.imageName.ToString()
为我提供了字符串 System.Drawing.Bitmap
您可以创建一个函数:
public static string GetPropertyName<T>(Expression<Func<T>> propertyExpression)
{
return (propertyExpression.Body as MemberExpression).Member.Name;
}
然后这样使用:
public class ClassName {
public Foo { get; set; }
}
...
...
...
var inst = new ClassName();
var propertyName = GetPropertyName(() => inst.Foo);
这不是我想出来的,我从其他主题中得到它 运行 看看它是否有效,但我的浏览器崩溃了,我找不到 link到原来的话题。我一找到就编辑我的post。
编辑:I've found it! 这是我摘录的地方。祝你好运。
Edit2:如果您能够轻松获得 resource.imageName,则只需将其传递给 GetPropertyName 函数即可。如果没有,我想我的回答不完整
在 Visual Studio 2015 年您可以使用 nameof()
string s = nameof(Resource1.myfile); // s = "myfile"
我尝试了几种方法来获取名称,包括调查 PropertyItems
和老式的 ToString()
方法来尝试获取图像资源的名称作为字符串。
我在资源文件中选择了一组图像,命名为。使用 resource.imageName
显示图像没有问题。我想尝试将 imageName
作为字符串来减少代码中其他地方的错误和拼写错误。
使用 resource.imageName.ToString()
为我提供了字符串 System.Drawing.Bitmap
您可以创建一个函数:
public static string GetPropertyName<T>(Expression<Func<T>> propertyExpression)
{
return (propertyExpression.Body as MemberExpression).Member.Name;
}
然后这样使用:
public class ClassName {
public Foo { get; set; }
}
...
...
...
var inst = new ClassName();
var propertyName = GetPropertyName(() => inst.Foo);
这不是我想出来的,我从其他主题中得到它 运行 看看它是否有效,但我的浏览器崩溃了,我找不到 link到原来的话题。我一找到就编辑我的post。
编辑:I've found it! 这是我摘录的地方。祝你好运。
Edit2:如果您能够轻松获得 resource.imageName,则只需将其传递给 GetPropertyName 函数即可。如果没有,我想我的回答不完整
在 Visual Studio 2015 年您可以使用 nameof()
string s = nameof(Resource1.myfile); // s = "myfile"