大写首字母和姓氏的问题

时间:2014-06-30 15:09:32

标签: c# .net web

我正在尝试将名字的第一个字母,中间名和姓氏大写。
我正在尝试使用 System.Globalization.TextInfo.ToTitleCase(newUser.Firstname),但我在visual studio中收到错误说“非静态字段需要对象引用,方法或财产“。帮助我解决这个问题:

public static UserAccount CreateUser(string firstName, string middleName, string lastName, string nameSuffix, int yearOfBirth, int? monthOfBirth, int? dayOfBirth, string email, string password, UserRole roles, bool tosAccepted = false)
{
    var newUser = new UserAccount
    {
        CreationDate = DateTime.Now,
        ActivationCode = Guid.NewGuid(),
        FirstName = firstName,
        MiddleName = middleName,
        LastName = lastName,
        NameSuffix = nameSuffix,
        YearOfBirth = yearOfBirth,
        MonthOfBirth = monthOfBirth,
        DayOfBirth = dayOfBirth,
        Email = email,
        UserRoles = roles,
        ToSAccepted = tosAccepted
    };
    string newUsers= System.Globalization.TextInfo.ToTitleCase(newUser.FirstName);
    newUser.SetPassword(password);
    return newUser;
}

2 个答案:

答案 0 :(得分:5)

ToTitleCase是一种实例方法,因此您必须通过对TextInfo实例的引用来调用它。您可以从当前线程的文化中获取TextInfo的实例,如下所示:

var textInfo = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo;

或者来自这样的特定文化:

var textInfo = new CultureInfo("en-US",false).TextInfo;

此外,它返回一个新字符串,而不是修改您传入的字符串。请尝试这样的事情:

public static UserAccount CreateUser(string firstName, string middleName, string lastName, string nameSuffix, int yearOfBirth, int? monthOfBirth, int? dayOfBirth, string email, string password, UserRole roles, bool tosAccepted = false)
{
    var textInfo = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo;

    var newUser = new UserAccount
    {
        CreationDate = DateTime.Now,
        ActivationCode = Guid.NewGuid(),
        FirstName = textInfo.ToTitleCase(firstName),
        MiddleName = middleName,
        LastName = textInfo.ToTitleCase(lastName),
        NameSuffix = nameSuffix,
        YearOfBirth = yearOfBirth,
        MonthOfBirth = monthOfBirth,
        DayOfBirth = dayOfBirth,
        Email = email,
        UserRoles = roles,
        ToSAccepted = tosAccepted
    };
    newUser.SetPassword(password);
    return newUser;
}

答案 1 :(得分:2)

您可以调用CultureInfo.CurrentCulture.TextInfo.ToTitleCase方法为您执行此操作:

CultureInfo.CurrentCulture.TextInfo.ToTitleCase(lastName)